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 returning in the first iteration of the loop. – Felix Kling Commented Feb 14, 2017 at 21:06
Add a ment  | 

1 Answer 1

Reset to default 6

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;
}

本文标签: javascriptiterating through words in a stringStack Overflow