Skip to content

Get first letter of each word JavaScript | Example code

  • by

Use match() method with RegEx and join() method to get first letter of each word in JavaScript. Where join method 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:

Get first letter of each word JavaScript

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

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

Leave a Reply

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