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

后端 未结 4 1233
栀梦
栀梦 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条回答
  • 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(''));

    0 讨论(0)
  • 2020-12-24 05:41

    Well, you can use this:

    var reg = new RegExp(oldWord, "g");
    myString.replace(reg, "");
    

    or simply:

    myString.replace(new RegExp(oldWord, "g"), "");
    
    0 讨论(0)
  • 2020-12-24 05:46

    You have to use the constructor rather than the literal syntax when passing variables. Stick with the literal syntax for literal strings to avoid confusing escape syntax.

    var oldWordRegEx = new RegExp(oldWord,'g');
    
    myString.replace(oldWordRegEx,"");
    
    0 讨论(0)
  • 2020-12-24 05:47

    According to the docs at MDN, you can do this:

    var re = /apples/gi;
    var str = 'Apples are round, and apples are juicy.';
    var newstr = str.replace(re, 'oranges');
    console.log(newstr);  // oranges are round, and oranges are juicy.
    

    where /gi tells it to do a global replace, ignoring case.

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