Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the last word from a string in Javascript [closed]

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
like image 258
user2238083 Avatar asked Jun 15 '13 03:06

user2238083


People also ask

How do I get the last word of a string?

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.

How do I get the last letter back in JavaScript?

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 .

How do you get rid of the last character in a string JavaScript?

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


3 Answers

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.

like image 164
Niet the Dark Absol Avatar answered Sep 24 '22 05:09

Niet the Dark Absol


var word = str.split("-").pop();
like image 26
Zero Fiber Avatar answered Sep 25 '22 05:09

Zero Fiber


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

like image 42
Beetroot-Beetroot Avatar answered Sep 22 '22 05:09

Beetroot-Beetroot