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

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

    The regular expression versions for JavaScript is not compatible with Unicode on older than ECMAScript 6, so for those who want to support characters such as "å" will need to rely on non-regex versions of scripts.

    Event when on version 6, you need to indicate Unicode with \u.

    More details: https://mathiasbynens.be/notes/es6-unicode-regex

    0 讨论(0)
  • 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);

    0 讨论(0)
  • 2020-12-05 04:42

    Yet another option using reduce function:

    var value = "Java Script Object Notation";
    
    var result = value.split(' ').reduce(function(previous, current){
        return {v : previous.v + current[0]};
    },{v:""});
    
    
    $("#output").text(result.v);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <pre id="output"/>

    0 讨论(0)
  • 2020-12-05 04:45

    If you came here looking for how to do this that supports non-BMP characters that use surrogate pairs:

    initials = str.split(' ')
                  .map(s => String.fromCodePoint(s.codePointAt(0) || '').toUpperCase())
                  .join('');
    

    Works in all modern browsers with no polyfills (not IE though)

    0 讨论(0)
  • 2020-12-05 04:48

    I think you can do this with

    'Aa Bb'.match(/\b\w/g).join('')
    

    Explanation: Obtain all /g the alphanumeric characters \w that occur after a non-alphanumeric character (i.e: after a word boundary \b), put them on an array with .match() and join everything in a single string .join('')


    Depending on what you want to do you can also consider simply selecting all the uppercase characters:

    'JavaScript Object Notation'.match(/[A-Z]/g).join('')
    
    0 讨论(0)
提交回复
热议问题