12

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

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

Closed-Flat-Knit-Collar
Flat-Woven-Collar
Fabric-Collar
Fabric-Closed-Flat-Knit-Collar
1
  • 4
    I don't think it is a localized question. And it has been viewed by 2100 users by now. I have voted for reopen
    – LCJ
    Jul 16, 2014 at 17:19

5 Answers 5

37

Why must everything be in 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.

1
  • 1
    Thanks for the explanation! Your correct, I should have just said JS. Jun 15, 2013 at 3:47
8
var word = str.split("-").pop();
6

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

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

DEMO

0
3

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

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

Pop works well -- here's an alternative:

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

Or perhaps more simplified as per comments:

var last = str.substring(str.lastIndexOf("-") + 1);
2
  • 1
    The second argument of substring is optional. Omitting it will return everything up to the end of the string. Jun 15, 2013 at 3:44
  • @Kolink -- agreed, just have always been explicit. I prefer using pop, just like to alter alternative option. Thanks.
    – sgeddes
    Jun 15, 2013 at 3:47

Not the answer you're looking for? Browse other questions tagged or ask your own question.