Categories
JavaScript Answers

How to Get the First Letter of Each Word in a String with JavaScript?

Spread the love

To get the first letter of each word in a string with JavaScript, we can find the first letter of each word with the match method.

Then we can join them together with join .

For instance, we can write:

const str = "Java Script Object Notation";
const matches = str.match(/\b(\w)/g);
const acronym = matches.join('');
console.log(acronym)

We have the str string, which we call match on with the /\b(\w)/g regex pattern to find all the letters that come after a space or the first letter in the string.

The g means we do the search globally.

\w matches letters and \b matches word boundaries.

matches returns all the matched letters in an array, so we can call join with an empty string to join them together into one string.

And therefore, acronym is 'JSON' .

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *