Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iterating through words in a string

Tags:

javascript

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;
  }
}
like image 451
Andrew Schittone Avatar asked Feb 14 '17 21:02

Andrew Schittone


1 Answers

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;
}
like image 144
Punith R Kashi Avatar answered Nov 02 '22 05:11

Punith R Kashi