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

后端 未结 4 1253
栀梦
栀梦 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: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,"");
    

提交回复
热议问题