Andrew Schittone
Andrew Schittone

Reputation: 91

iterating through words in a string

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

Answers (1)

Punith R Kashi
Punith R Kashi

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

Related Questions