myString.replace( VARIABLE, "") ...... but globally
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(''));
monkey blot
Updated on July 09, 2022Comments
-
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 朕會功夫 about 12 yearsWoot! Is that copying from me?
-
Erik Reppen about 12 yearsI just type slower and offer more advice.
-
Erik Reppen about 12 yearsSigh... always a bridesmaid never an answer.
-
Camilo Martin over 9 yearsBoom:
var oldWord = '\\';
-
Derek 朕會功夫 almost 9 yearsThis does not answer the question.
-
bra_racing over 5 yearsThe question is about replacing the content of a variable