how to remove the last word in the string using JavaScript

后端 未结 9 1016
轻奢々
轻奢々 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:17

    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(" "));
    
    0 讨论(0)
  • 2020-12-08 19:18
    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.

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

    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(' '));
    
    0 讨论(0)
  • 2020-12-08 19:22

    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(" ")
    
    0 讨论(0)
  • 2020-12-08 19:27

    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])
    
    0 讨论(0)
  • 2020-12-08 19:36

    Use split function

    var myString = "I want to remove the last word";
    var mySplitResult = myString.split(" ");
    var lastWord =  mySplitResult[mySplitResult.length-1] 
    
    0 讨论(0)
提交回复
热议问题