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

javascript, replace, string, variables

Solution

Well, you can use this:

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

or simply:

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

Problem

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?

Original source