Redwall Redwall - 1 year ago 99
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
and looked here 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 Source

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

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

\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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download