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
Following answer by Amir Raminfar, I found this solution. In my opinion, it's better than accepted answer, because it works even if you have a space at the end of the string or with languages (like French) that have spaces between last word and punctuation mark.
"Je veux supprimer le dernier mot !".replace(/[\W]*\S+[\W]*$/, '')
"Je veux supprimer le dernier"
It strips also the space(s) and punctuation marks before the last word, as the OP implicitly required.
Peace.
If anyone else here is trying to split a string name in to last name and first name, please make sure to handle the case in which the name has only word.
let recipientName = _.get(response, 'shipping_address.recipient_name');
let lastWordIndex = recipientName.lastIndexOf(" ");
let firstName = (lastWordIndex == -1) ? recipientName : recipientName.substring(0, lastWordIndex);
let lastName = (lastWordIndex == -1) ? '' : recipientName.substring(lastWordIndex + 1);
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.