Redwall Redwall - 16 days ago 5
Javascript Question

Return First Character of each word in a string

I have a string with Names and I want to convert them to Initials. E.g:


  • John White -> JW

  • John P White -> JPW



I am looking for a suggesting on how best to do this. I have researched using
split()
and looked here http://www.w3schools.com/jsref/jsref_split.asp but could not find a good example of how to target and return first letter when I don't know the char to look for.

My string looks like this

<a href="#">John White</a>


and I want to change to this

<a href="#">JW</a>


Any help? Thanks

Answer

I would suggest you to use RegExp, Here's an Example

var myStr = "John P White";
var matches = myStr.match(/\b(\w)/g);
alert(matches.join(''));

\b assert position at a word boundary (^\w|\w$|\W\w|\w\W)

1st Capturing Group (\w)

\w matches any word character (equal to [a-zA-Z0-9_])

Global pattern flags

g modifier: global. All matches (don't return after first match)

For better explanation visit here