Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get first letter of each word in a string, in JavaScript

Tags:

javascript

How would you go around to collect the first letter of each word in a string, as in to receive an abbreviation?

Input: "Java Script Object Notation"

Output: "JSON"

like image 680
Gerben Jacobs Avatar asked Nov 26 '11 16:11

Gerben Jacobs


People also ask

How do you get the first letter in a string JavaScript?

Get the First Letter of the String You should use the charAt() method, at index 0, to select the first character of the string. NOTE: charAt is preferable than using [ ] (bracket notation) as str. charAt(0) returns an empty string ( '' ) for str = '' instead of undefined in case of ''[0] .

How do you capitalize the first letter of each word in a string in JavaScript?

In JavaScript, we have a method called toUpperCase() , which we can call on strings, or words. As we can imply from the name, you call it on a string/word, and it is going to return the same thing but as an uppercase. For instance: const publication = "freeCodeCamp"; publication[0].

How do I get the first letter of a word in jquery?

var header = $('. time'+col). text(); alert(header);

How can we iterate through individual words in a string JavaScript?

Simple for loop can use for in iterate through words in a string JavaScript. And for iterate words in string use split, map, and join methods (functions).


1 Answers

I think what you're looking for is the acronym of a supplied string.

var str = "Java Script Object Notation";  var matches = str.match(/\b(\w)/g); // ['J','S','O','N']  var acronym = matches.join(''); // JSON    console.log(acronym)

Note: this will fail for hyphenated/apostrophe'd words Help-me I'm Dieing will be HmImD. If that's not what you want, the split on space, grab first letter approach might be what you want.

Here's a quick example of that:

let str = "Java Script Object Notation";  let acronym = str.split(/\s/).reduce((response,word)=> response+=word.slice(0,1),'')    console.log(acronym);
like image 174
BotNet Avatar answered Oct 20 '22 13:10

BotNet