myString.replace( VARIABLE, “”) … but globally

后端 未结 4 1254
栀梦
栀梦 2020-12-24 04:51

How can I use a variable to remove all instances of a substring from a string? (to remove, I\'m thinking the best way is to replace, with nothing, globally... right?)

<
4条回答
  •  -上瘾入骨i
    2020-12-24 05:40

    No need to use a regular expression here: split the string around matches of the substring you want to remove, then join the remaining parts together:

    myString.split(oldWord).join('')
    

    In the OP's example:

    var myString = "This sentence is an example sentence.";
    var oldWord = " sentence";
    console.log(myString.split(oldWord).join(''));

提交回复
热议问题