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

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 Notation"

Output: "JSON"


Solution 1:

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

Solution 2:

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('')

Solution 3:

Easiest way without regex

var abbr = "Java Script Object Notation".split(' ').map(function(item){return item[0]}).join('');