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

后端 未结 17 1633
后悔当初
后悔当初 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:39

    Alternative 1:

    you can also use this regex to return an array of the first letter of every word

    /(?<=(\s|^))[a-z]/gi
    

    (?<=(\s|^)) is called positive lookbehind which make sure the element in our search pattern is preceded by (\s|^).


    so, for your case:

    // in case the input is lowercase & there's a word with apostrophe
    
    const toAbbr = (str) => {
      return str.match(/(?<=(\s|^))[a-z]/gi)
                .join('')
                .toUpperCase();
    };
    
    toAbbr("java script object notation"); //result JSON
    

    (by the way, there are also negative lookbehind, positive lookahead, negative lookahead, if you want to learn more)


    Alternative 2:

    match all the words and use replace() method to replace them with the first letter of each word and ignore the space (the method will not mutate your original string)

    // in case the input is lowercase & there's a word with apostrophe    
    
    const toAbbr = (str) => {
      return str.replace(/(\S+)(\s*)/gi, (match, p1, p2) => p1[0].toUpperCase());
    };
    
    toAbbr("java script object notation"); //result JSON
    
    // word = not space = \S+ = p1 (p1 is the first pattern)
    // space = \s* = p2 (p2 is the second pattern)
    

提交回复
热议问题