admin管理员组文章数量:1289893
I'm trying to abbreviate all words in a given string with the code below, however I can only get it to alter the first word of every string. What am I doing wrong?
function abbreviate(string) {
var words = string.split(" ");
for (var i = 0; i < words.length; i += 1) {
var count = words[i].length - 2;
var last = words[i].charAt(words[i].length - 1);
return words[i][0] + count + last;
}
}
I'm trying to abbreviate all words in a given string with the code below, however I can only get it to alter the first word of every string. What am I doing wrong?
function abbreviate(string) {
var words = string.split(" ");
for (var i = 0; i < words.length; i += 1) {
var count = words[i].length - 2;
var last = words[i].charAt(words[i].length - 1);
return words[i][0] + count + last;
}
}
Share
Improve this question
asked Feb 14, 2017 at 21:04
Andrew SchittoneAndrew Schittone
911 gold badge1 silver badge3 bronze badges
1
-
9
"What am I doing wrong?" You are
return
ing in the first iteration of the loop. – Felix Kling Commented Feb 14, 2017 at 21:06
1 Answer
Reset to default 6I think this solves your problem
function abbreviate(string) {
var words = string.split(" ");
var answer = "";
for (var i = 0; i < words.length; i += 1) {
var count = words[i].length - 2;
var last = words[i].charAt(words[i].length - 1);
answer= answer + words[i][0] + count + last;
}
return answer;
}
本文标签: javascriptiterating through words in a stringStack Overflow
版权声明:本文标题:javascript - iterating through words in a string - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741463900a2380196.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论