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

后端 未结 4 1232
栀梦
栀梦 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: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.

提交回复
热议问题