Find the first letter of the last word with jquery inside a string (a string can contain several words)

Hy, is there a way to find the first letter of the last word in a string? Strings are the result of an XML parser function. Inside each () loop, I get all the nodes and put each name inside the variable as follows: var person = xml.find ("name"). Find (). Text ()

Now the person holds a line, it can be:

  • Anamaria Forrest Gump
  • John lock

As you can see, the first line contains 3 words, and the second - 2 words.

I need the first letters of the last words: "G", "L",

How to do it? Ty

+2
source share
3 answers

This should do it:

var person = xml.find("name").find().text(); var names = person.split(' '); var firstLetterOfSurname = names[names.length - 1].charAt(0); 
+4
source

This solution will work even if your line contains one word. It returns the desired character:

 myString.match(/(\w)\w*$/)[1]; 

Explanation: "Match the word character (and remember it) (\w) , then match any number of word characters \w* , and then match the end of the string $ ." In other words: "Match the sequence of word characters at the end of the line (and remember the first of these word characters)." match returns an array with all matches in [0] , and then the stored strings in [1] , [2] , etc. Here we want [1] .

Regular expressions are enclosed in / in javascript: http://www.w3schools.com/js/js_obj_regexp.asp

+1
source

You can crack it with a regex:

 'Marry Jo Poppins'.replace(/^.*\s+(\w)\w+$/, "$1"); // P 'Anamaria Forrest Gump'.replace(/^.*\s+(\w)\w+$/, "$1"); // G 

Otherwise, Mark B's answer is fine too :)


Edit

Alsciende regex + javascript combo myString.match(/(\w)\w*$/)[1] is probably a bit more versatile than mine.

regular expression explanation

 /^.*\s+(\w)\w+$/ ^ beginning of input string .* followed by any character (.) 0 or more times (*) \s+ followed by any whitespace (\s) 1 or more times (+) ( group and capture to $1 \w followed by any word character (\w) ) end capture \w+ followed by any word character (\w) 1 or more times (+) $ end of string (before newline (\n)) 

Re-expression of Alsciende

 /(\w)\w*$/ ( group and capture to $1 \w any word character ) end capture \w* any word character (\w) 0 or more times (*) 

Summary

Regular expressions are extremely effective, or, as you might say, "God!" Regular-Expressions.info is a great starting point if you want to know more.

Hope this helps :)

0
source

All Articles