I have a string with Names and I want to convert them to Initials. E.g:
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
By the help of split ("\s") method, we can get all words in an array. To get the first character, we can use substring () or charAt () method. Let's see the example to reverse each word in a string.
To get first word in string we will split the string by space. Hence the pattern to denote the space in regex is “s”. Above we have solved python get first word in string in 3 ways. We can get first word in string in python by using string split () method, re.split () and by using for loop. I am Passionate Computer Engineer.
Java Program to reverse each word in String We can reverse each word of a string by the help of reverse (), split () and substring () methods. By using reverse () method of StringBuilder class, we can reverse given string. By the help of split ("\s") method, we can get all words in an array.
1 Run a loop from the first letter to the last letter. 2 Print the first and last letter of the string. 3 If there is a space in the string then print the character that lies just before space and just after space. More ...
I would suggest you to use RegExp
, Here's an Example
var myStr = "John P White";
var matches = myStr.match(/\b(\w)/g);
console.log(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
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