Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 201
Redwall Avatar asked Feb 21 '14 10:02

Redwall


People also ask

How to get the first character of a string in JavaScript?

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.

How to get first word in string in Python?

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.

How to reverse each word in string in Java?

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.

How to print the first and last letter of a string?

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 ...


1 Answers

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

like image 137
Satpal Avatar answered Nov 02 '22 23:11

Satpal