Skip to content Skip to sidebar Skip to footer

Getting The Last Word From A String In Javascript

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

Solution 1:

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.

Solution 2:

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

Solution 3:

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

Solution 4:

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

Solution 5:

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

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

Post a Comment for "Getting The Last Word From A String In Javascript"