Use the match() method with RegEx and join() method to get first letter of each word in JavaScript. Where join method is to join the array into a string.
Get the first letter of each word in JavaScript
Simple example code.
<!DOCTYPE html>
<html>
<body>
<script>
var str = "Java Script Object Notation";
var matches = str.match(/\b(\w)/g);
var acronym = matches.join('');
console.log(acronym)
</script>
</body>
</html>
Output:
Another way
let str = "Java Script Object Notation";
let acronym = str.split(/\s/).reduce((response,word)=> response+=word.slice(0,1),'')
console.log(acronym);
OR
function getFirstLetters(str) {
const firstLetters = str
.split(' ')
.map(word => word[0])
.join('');
return firstLetters;
}
// 👇️ ABC
console.log(getFirstLetters('Alice, Bob, Charlie'));
// 👇️ ONE
console.log(getFirstLetters('Oscar Noah Emily.'));
Or
To get the first letter of each word in a string using JavaScript, you can follow these steps:
- Split the string into an array of words using the
split()
method, which splits the string based on whitespace. - Iterate over each word in the array and extract the first letter using the
charAt()
method or by accessing the index[0]
. - Store the first letters in a new array or concatenate them into a new string.
- Optionally, join the first letters back together into a string using the
join()
method if you stored them in an array.
Here’s an example implementation:
function getFirstLetters(str) {
var words = str.split(' ');
var firstLetters = [];
for (var i = 0; i < words.length; i++) {
var word = words[i];
var firstLetter = word.charAt(0); // or word[0]
firstLetters.push(firstLetter);
}
var result = firstLetters.join('');
return result;
}
// Example usage
var sentence = "Hello World";
var firstLetters = getFirstLetters(sentence);
console.log(firstLetters); // Output: HW
Do comment if you have any doubts or suggestions on this JS code.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version