how to remove the last word in the string using JavaScript

后端 未结 9 1017
轻奢々
轻奢々 2020-12-08 18:45

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

相关标签:
9条回答
  • 2020-12-08 19:38

    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.

    0 讨论(0)
  • 2020-12-08 19:39

    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);

    0 讨论(0)
  • 2020-12-08 19:40

    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.

    0 讨论(0)
提交回复
热议问题