我试着写一个函数来缩写句子中的单词,其中一个单词中有4个或4个以上的字符。所以“骑大象真的很有趣!”变成"E6t-r3s是r4y的乐趣!“
我设法把所有的单词都缩略出来了,但我想不出有三件事。
编辑:我也会对一个非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 ");
发布于 2016-10-25 14:32:07
您可以查看每个字符,检查一个非字母,并重置计数器。如果找到一个字母,请检查计数,如果计数为零,则追加。
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"));.as-console-wrapper { max-height: 100% !important; top: 0; }
或者您可以使用正则表达式将单词替换为缩写。
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"));.as-console-wrapper { max-height: 100% !important; top: 0; }
发布于 2016-10-25 13:48:51
您可以使用\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"))
备注:
match和test。发布于 2022-09-10 15:23:08
const input = 'Elephant-rides are really fun ';
const result = input.split(/\W+/).filter(x => x).map(x => x.length < 4 ? x : x[0] + (x.length - 2) + x[x.length-1]);
console.log(result);
https://stackoverflow.com/questions/40241687
复制相似问题