how to remove the last word in the string using JavaScript

后端 未结 9 1069
轻奢々
轻奢々 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.

提交回复
热议问题