Categories
JavaScript Answers

How to get first letter of each word in a string in JavaScript?

Spread the love

Sometimes, we want to get first letter of each word in a string in JavaScript.

In this article, we’ll look at how to get first letter of each word in a string in JavaScript.

How to get first letter of each word in a string in JavaScript?

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

For instance, we write

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

console.log(acronym);

to call str.match with a regex to match the first letter after a word boundary.

We use the g flag to get all matches.

Then we call matches.join to combine the returned array of characters into a string.

Conclusion

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

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 *