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.
With split
and map
:
'John Cooper'.split(' ').map(function (s) { return s.charAt(0); }).join('');
With regular expressions:
'John Cooper'.replace(/[^A-Z]/g, '');
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With