在JavaScript中搜索最后一个单词 [英] Searching for a last word in JavaScript
本文介绍了在JavaScript中搜索最后一个单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在为句子上的最后一个字做一些逻辑。单词由空格或 - 字符分隔。
I am doing some logic for the last word that is on the sentence. Words are separated by either space or with a '-' character.
获取它的最简单方法是什么?
What is easiest way to get it?
编辑
我可以通过从句子末尾向后移动来做到这一点,但我想找到更好的方法
I could do it by traversing backwards from the end of the sentence, but I would like to find better way
推荐答案
尝试拆分匹配空格或连字符并使用最后一个元素的正则表达式:
Try splitting on a regex that matches spaces or hyphens and taking the last element:
var lastWord = function(o) {
return (""+o).replace(/[\s-]+$/,'').split(/[\s-]/).pop();
};
lastWord('This is a test.'); // => 'test.'
lastWord('Here is something to-do.'); // => 'do.'
正如@alex指出的那样,值得修剪任何尾随空格或连字符。确保参数是一个字符串也是一个好主意。
As @alex points out, it's worth trimming any trailing whitespace or hyphens. Ensuring the argument is a string is a good idea too.
这篇关于在JavaScript中搜索最后一个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文