开发者

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

Hy, is there a way to find the first letter of the last word in a string? The strings are results in a XML parser function. Inside the each() loop i get all the nodes and put every name inside a variable like this: var 开发者_如何学编程person = xml.find("name").find().text()

Now person holds a string, it could be:

  • Anamaria Forrest Gump
  • John Lock

As you see, the first string holds 3 words, while the second holds 2 words.

What i need are the first letters from the last words: "G", "L",

How do i accomplish this? TY


This should do it:

var person = xml.find("name").find().text();

var names = person.split(' ');
var firstLetterOfSurname = names[names.length - 1].charAt(0);


This solution will work even if your string contains a single word. It returns the desired character:

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

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

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


You can hack it with 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's regex+javascript combo myString.match(/(\w)\w*$/)[1] is probably a little 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))

Alsciende's regex

/(\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 awesomely powerful, or as you might say, "Godlike!" Regular-Expressions.info is a great starting point if you'd like to learn more.

Hope this helps :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜