开发者

Acronym generator in javascript. It only grabs the first letter of the first word, but the not the other words

开发者 https://www.devze.com 2023-03-08 20:46 出处:网络
Am I missing something in my code? It s开发者_StackOverflow中文版eems to only grab the first letter, and the while loop, doesn\'t go onto the next word. So what could I be missing?

Am I missing something in my code? It s开发者_StackOverflow中文版eems to only grab the first letter, and the while loop, doesn't go onto the next word. So what could I be missing?

function acr(s){
    var words, acronym, nextWord;

    words = s.split();
    acronym= "";
    index = 0
    while (index<words.length) {
            nextWord = words[index];
            acronym = acronym + nextWord.charAt(0);
            index = index + 1 ;
    }
    return acronym
}


If you only care about IE9+ then the answer can be made shorter:

function acronym(text) {
  return text
    .split(/\s/)
    .reduce(function(accumulator, word) {
      return accumulator + word.charAt(0);
    }, '');
}

console.log(acronym('three letter acronym'));

If you can use arrow functions then it can be made shorter still:

function acronym(text) {
  return text
    .split(/\s/)
    .reduce((accumulator, word) => accumulator + word.charAt(0), '');
}

console.log(acronym('three letter acronym'));


Add the separator to the split:

function acr(s){
    var words, acronym, nextWord;

    words = s.split(' ');
    acronym= "";
    index = 0
    while (index<words.length) {
            nextWord = words[index];
            acronym = acronym + nextWord.charAt(0);
            index = index + 1 ;
    }
    return acronym
}

JS Fiddle demo;

Revised the above to make it a little more demonstrative, and also interactive: JS Fiddle demo.


Edited to add references and explanation:

Because no separator was supplied the string remains un-split; therefore the while was operating correctly (as words.length is equal to 1), and so returns only the first letter of the string:

[Separator] specifies the character to use for separating the string. The separator is treated as a string or a regular expression. If separator is omitted, the array returned contains one element consisting of the entire string.

Reference:

  • split(), at MDC Docs


You forgot to split on whitespace:

words = s.split(/\s/);


You can have this in even lesser code. Try this

s.match(/\b(\w)/g).join("").toUpperCase()
0

精彩评论

暂无评论...
验证码 换一张
取 消