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

时间:2021-03-04 22:22:29

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

5 个解决方案

#1


32  

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.

这会将您的字符串分成单独的组件(例如,封闭,平面,针织,衣领)。然后它将弹出数组的最后一个元素并返回它。在你给出的所有例子中,这是Collar。

#2


7  

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

#3


5  

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()答案,所以对于completness,这是一个正则表达式方法:

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

DEMO

DEMO

#4


3  

Pop works 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);

#5


2  

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

你不需要jQuery来做到这一点。您可以使用纯JavaScript:

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

#1


32  

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.

这会将您的字符串分成单独的组件(例如,封闭,平面,针织,衣领)。然后它将弹出数组的最后一个元素并返回它。在你给出的所有例子中,这是Collar。

#2


7  

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

#3


5  

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()答案,所以对于completness,这是一个正则表达式方法:

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

DEMO

DEMO

#4


3  

Pop works 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);

#5


2  

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

你不需要jQuery来做到这一点。您可以使用纯JavaScript:

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