我想實現的是一個字符串:的JavaScript:取每個單詞的前三個字母的字符串,每一個字後,把「_」
var string = "Hello there my friend";
,並返回一個格式化字符串如下:
"HEL_THE_MY_FRI"
所以我試圖把每個單詞的前三個字母在ST在每個環之後添加一個下劃線。在資本很容易:) .toUpperCase()
我想實現的是一個字符串:的JavaScript:取每個單詞的前三個字母的字符串,每一個字後,把「_」
var string = "Hello there my friend";
,並返回一個格式化字符串如下:
"HEL_THE_MY_FRI"
所以我試圖把每個單詞的前三個字母在ST在每個環之後添加一個下劃線。在資本很容易:) .toUpperCase()
你可以使用replace
爲:
var string = "Hello there my friend";
var result = string.toUpperCase().replace(/\b(\S{1,3})\S*/g, '$1').replace(/ /g, '_');
console.log(result);
既然你沒有提供到目前爲止你已經嘗試了任何代碼,你會採取的步驟是:
var phrase = 'this is my string';
var words = phrase.split(' ');
var result = '';
for (var i = 0; i < words.length; i++) {
var word = words[i];
result += word.substring(0, 3).toUpperCase();
if (i < words.length - 1) {
result += '_';
}
}
console.log(result);
console.log("Hello there my friend".split(" ").map((a)=>a.substring(0, 3)).join("_").toUpperCase());
LoL。你應該提供了Soviut的解釋! ':D' –
@PraveenKumar合併答案:P – Mahi
「一線」 使用String.replace()
,String.toUpperCase()
和String.slice()
功能解決方案:
var string = "Hello there my friend",
replaced = string.replace(/\b(\w{1,3})(\w+\s?|\s)/g, '$1_').toUpperCase().slice(0,-1);
console.log(replaced);
'my'字不包含三個字符,爲什麼後面跟着'_'? – RomanPerekhrest
@RomanPerekhrest我覺得解釋沒有考慮極端情況考慮在內。 – Soviut