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.