Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting the first character of the words

Tags:

javascript

I have a requirement where i have to take the first letter of two words alone. Like I get the response from the WebService as John Cooper and i have to take JC from this.

I tried sbstr(0,2), but this takes JO, is there any way we can form like above.

like image 824
John Cooper Avatar asked Nov 15 '11 08:11

John Cooper


2 Answers

With split and map:

'John Cooper'.split(' ').map(function (s) { return s.charAt(0); }).join('');

With regular expressions:

'John Cooper'.replace(/[^A-Z]/g, '');
like image 150
katspaugh Avatar answered Sep 29 '22 07:09

katspaugh


To generalize the regex answer given by @katspaugh, this will work for all strings with any number of words, whether or not the first letter is capitalized.

'John Cooper workz'.replace(/\W*(\w)\w*/g, '$1').toUpperCase()

will result in JCW

obviously if you want to keep the case of the first letter each word, just remove the toUpperCase()

SIDE NOTE

with this approach, things like John McCooper will result in JM not JMC

like image 33
ShaneA Avatar answered Sep 29 '22 07:09

ShaneA