Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove the last word in a string using JavaScript

Tags:

javascript

How can I remove the last word in the string using JavaScript?

For example, the string is "I want to remove the last word."

After using removal, the string in the textbox will display "I want to remove the last"

I've seen how to remove the last character using the substring function, but because the last word can be different every time. Is there a way to count how many words are required to remove in JavaScript?

like image 365
R.Spark Avatar asked Feb 17 '12 05:02

R.Spark


People also ask

How do you delete 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) .

How do I get the last word in JavaScript?

To get the last word of a string:Call the split() method on the string, passing it a string containing an empty space as a parameter. The split method will return an array containing the words in the string. Call the pop() method to get the value of the last element (word) in the array.


1 Answers

Use:

var str = "I want to remove the last word."; var lastIndex = str.lastIndexOf(" ");  str = str.substring(0, lastIndex); 

Get the last space and then get the substring.

like image 130
Sean Avatar answered Oct 14 '22 02:10

Sean