Reputation: 91
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;
}
}
Upvotes: 9
Views: 20425
Reputation: 149
I 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;
}
Upvotes: 6