I would like to know 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 usin
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(" "));
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.
The shortest answer to this question would be as below,
var str="I want to remove the last word".split(' ');
var lastword=str.pop();
console.log(str.join(' '));
Fooling around just for fun, this is a funny and outrageous way to do it!
"I want to remove the last word.".split(" ").reverse().slice(1).reverse().join(" ")
You can match the last word following a space that has no word characters following it.
word=/s+\W*([a-zA-Z']+)\W*$/.exec(string);
if(word) alert(word[1])
Use split
function
var myString = "I want to remove the last word";
var mySplitResult = myString.split(" ");
var lastWord = mySplitResult[mySplitResult.length-1]