how to remove the last word in the string using JavaScript

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

str = str.substring(0, lastIndex);

Get last space and then get sub string.


An easy way to do that would be to use JavaScript's lastIndexOf() and substr() methods:

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

You can do a simple regular expression like so:

"I want to remove the last word.".replace(/\w+[.!?]?$/, '')
>>> "I want to remove the last"

Finding the last index for " " is probably faster though. This is just less code.

Tags:

Javascript