jQuery 从Javascript中的字符串中获取最后一个单词

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17119959/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 18:28:52  来源:igfitidea点击:

Getting the last word from a string in Javascript

javascriptjquerystring

提问by user2238083

How can we get the last word from a string using JavaScript / jQuery?

我们如何使用 JavaScript / jQuery 从字符串中获取最后一个单词?

In the following scenario the last word is "Collar". The words are separated by "-".

在下面的场景中,最后一个词是“Collar”。单词以“-”分隔。

Closed-Flat-Knit-Collar
Flat-Woven-Collar
Fabric-Collar
Fabric-Closed-Flat-Knit-Collar

回答by Niet the Dark Absol

Why must everything be in jQuery?

为什么一切都必须在 jQuery 中?

var lastword = yourString.split("-").pop();

This will split your string into the individual components (for exampe, Closed, Flat, Knit, Collar). Then it will pop off the last element of the array and return it. In all of the examples you gave, this is Collar.

这会将您的字符串拆分为单个组件(例如,ClosedFlatKnitCollar)。然后它将弹出数组的最后一个元素并返回它。在您提供的所有示例中,这是Collar.

回答by Zero Fiber

var word = str.split("-").pop();

回答by Beetroot-Beetroot

I see there's already several .split().pop()answers and a substring()answer, so for completness, here's a Regular Expression approach :

我看到已经有几个.split().pop()答案和一个substring()答案,所以为了完整起见,这是一个正则表达式方法:

var lastWord = str.match(/\w+$/)[0];

DEMO

演示

回答by sgeddes

Popworks well -- here's an alternative:

Pop效果很好——这里有一个替代方案:

var last = str.substring(str.lastIndexOf("-") + 1, str.length);

Or perhaps more simplified as per comments:

或者根据评论可能更简化:

var last = str.substring(str.lastIndexOf("-") + 1);

回答by Praveen Kumar Purushothaman

You don't need jQuery to do this. You can do with pure JavaScript:

您不需要 jQuery 来执行此操作。您可以使用纯 JavaScript:

var last = strLast.split("-").pop();