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