myString.replace( VARIABLE, "") ...... but globally

72,606

Solution 1

Well, you can use this:

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

or simply:

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

Solution 2

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,"");

Solution 3

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(''));

Share:
72,606
monkey blot
Author by

monkey blot

Updated on July 09, 2022

Comments

  • monkey blot
    monkey blot almost 2 years

    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?)

    if I have these 2 strings,

    myString = "This sentence is an example sentence."
    oldWord = " sentence"
    

    then something like this

    myString.replace(oldWord, "");
    

    only replaces the first instance of the variable in the string.

    but if I add the global g like this myString.replace(/oldWord/g, ""); it doesn't work, because it thinks oldWord, in this case, is the substring, not a variable. How can I do this with the variable?

  • Derek 朕會功夫
    Derek 朕會功夫 about 12 years
    Woot! Is that copying from me?
  • Erik  Reppen
    Erik Reppen about 12 years
    I just type slower and offer more advice.
  • Erik  Reppen
    Erik Reppen about 12 years
    Sigh... always a bridesmaid never an answer.
  • Camilo Martin
    Camilo Martin over 9 years
    Boom: var oldWord = '\\';
  • Derek 朕會功夫
    Derek 朕會功夫 almost 9 years
    This does not answer the question.
  • bra_racing
    bra_racing over 5 years
    The question is about replacing the content of a variable