我试图编写一个函数来缩写句子中的单词,其中单词中有4个或更多个字符。所以"象骑很有趣!"成为" E6t-r3s很有趣!"。
我设法赶到我缩写所有单词的地方,但我无法弄清楚三件事。
编辑:我也会对非RegEx答案感兴趣(虽然已经发布的答案很有帮助),因为我是编程的新手并且仍在努力计算循环。
function abbrv(str) {
var word=""
var newStr=""
var counter= 0
var oldCounter= 0
for (var i=0; i<str.length; i+=1){
counter+= 1
word+= str[i]
if(str[i]===" "||str[i]==="-"){
newStr += word[oldCounter]+(counter-(oldCounter+3)).toString()+word[counter-2]+str[i]
oldCounter= counter
}
}
console.log(newStr)
}
abbrv("Elephant-rides are really fun ");
&#13;
答案 0 :(得分:2)
您可以使用\b
正则表达式匹配单词:
function abbrWord(word) {
if (word.length <= 3) return word; // This also filters out ", " or "-"
return word[0] +
(word.length - 2) +
word[word.length - 1];
}
function abbrv(str) {
return str.split(/\b/) // Create an array of words and word boundaries
.map(abbrWord) // for each item in the array, replace with abbr.
.join(""); // join items together to form a string
}
console.log(abbrv("Elephant-rides are really fun"))
&#13;
注意:
match
和test
。答案 1 :(得分:1)
您可以查看每个字符并检查非字母并重置计数器。如果找到了一个字母,检查计数并在计数为零时附加。
function abbrv(str) {
var newStr = "",
count = 0,
i;
for (i = 0; i < str.length; i++) {
if (str[i] === " " || str[i] === "-") {
if (count > 0) {
newStr += count > 3 ? count - 2 : str[i - 2];
newStr += str[i - 1];
}
newStr += str[i];
count = 0;
continue;
}
if (count === 0) {
newStr += str[i];
}
count++;
}
if (count > 0) {
newStr += count > 3 ? count - 2 : str[i - 2];
newStr += str[i - 1];
}
return newStr;
}
console.log(abbrv("Elephant-rides are really funy"));
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
或者您可以使用正则表达式替换缩写词。
function abbrv(str) {
return str.replace(/\w{4,}/g, function (s) {
var l = s.length;
return s[0] + (l - 2) + s[l - 1];
});
}
console.log(abbrv("Elephant-rides are really fun"));
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;