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
Using the split() Method As we have to get the last word of a string, we'll be using space (” “) as a regular expression to split the string. This will return “day”, which is the last word of our input string.
String charAt() Method Alternatively, to get the last character of a string, we can call the charAt() method on the string, passing the last character index as an argument. For example, str. charAt(str. length - 1) returns a new string containing the last character of str .
To remove the last character from a string in JavaScript, you should use the slice() method. It takes two arguments: the start index and the end index. slice() supports negative indexing, which means that slice(0, -1) is equivalent to slice(0, str. length - 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
.
var word = str.split("-").pop();
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With