在字符串中用jquery查找最后一个单词的第一个字母(字符串可以有多个单词)
Hy,有没有办法找到字符串中最后一个单词的第一个字母? 字符串是XML解析器函数的结果。 在each()循环中,我获取所有节点并将每个名称放在一个变量中,如下所示:var person = xml.find(“name”)。find()。text()
现在人持有一个字符串,它可能是:
- Anamaria Forrest Gump
- 约翰洛克
如您所见,第一个字符串包含3个单词,而第二个字符串包含2个单词。
我需要的是最后一个字的第一个字母:“G”,“L”,
我该如何做到这一点? TY
这应该这样做:
var person = xml.find("name").find().text(); var names = person.split(' '); var firstLetterOfSurname = names[names.length - 1].charAt(0);
即使您的字符串包含单个单词,此解决方案也可以使用。 它返回所需的字符:
myString.match(/(\w)\w*$/)[1];
说明:“匹配单词字符(并记住它) (\w)
,然后匹配任意数量的单词字符\w*
,然后匹配字符串$
”的结尾。 换句话说:“匹配字符串末尾的一系列单词字符(并记住这些单词字符中的第一个)”。 match
返回一个数组,其中包含[0]
的整个匹配,然后是[1]
, [2]
等中记忆的字符串。这里我们想要[1]
。
正则表达式包含在javascript中: http : //www.w3schools.com/js/js_obj_regexp.asp
你可以用正则表达式破解它:
'Marry Jo Poppins'.replace(/^.*\s+(\w)\w+$/, "$1"); // P 'Anamaria Forrest Gump'.replace(/^.*\s+(\w)\w+$/, "$1"); // G
否则Mark B的答案也很好:)
编辑:
Alsciende的正则表达式+ javascript组合myString.match(/(\w)\w*$/)[1]
可能比我的多才多艺。
正则表达式解释
/^.*\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的正则表达式
/(\w)\w*$/ ( group and capture to $1 \w any word character ) end capture \w* any word character (\w) 0 or more times (*)
摘要
正则表达式非常强大,或者你可能会说,“像上帝一样!” 如果您想了解更多, Regular-Expressions.info是一个很好的起点。
希望这可以帮助 :)