Get first letter of each word in a string, in JavaScript

后端 未结 17 1668
后悔当初
后悔当初 2020-12-05 04:00

How would you go around to collect the first letter of each word in a string, as in to receive an abbreviation?

Input: "Java Script Object

17条回答
  •  甜味超标
    2020-12-05 04:42

    I think what you're looking for is the acronym of a supplied string.

    var str = "Java Script Object Notation";
    var matches = str.match(/\b(\w)/g); // ['J','S','O','N']
    var acronym = matches.join(''); // JSON
    
    console.log(acronym)


    Note: this will fail for hyphenated/apostrophe'd words Help-me I'm Dieing will be HmImD. If that's not what you want, the split on space, grab first letter approach might be what you want.

    Here's a quick example of that:

    let str = "Java Script Object Notation";
    let acronym = str.split(/\s/).reduce((response,word)=> response+=word.slice(0,1),'')
    
    console.log(acronym);

提交回复
热议问题