53

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?

monkey blot
  • 985
  • 3
  • 10
  • 18
  • 1
    possible duplicate of [How do you pass a variable to a Regular Expression JavaScript?](http://stackoverflow.com/questions/494035/how-do-you-pass-a-variable-to-a-regular-expression-javascript) – fxp Nov 06 '13 at 07:47

4 Answers4

94

Well, you can use this:

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

or simply:

myString.replace(new RegExp(oldWord, "g"), "");
Steffan
  • 704
  • 1
  • 11
  • 25
Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
12

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,"");
Erik Reppen
  • 4,605
  • 1
  • 22
  • 26
7

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(''));
GOTO 0
  • 42,323
  • 22
  • 125
  • 158
-2

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.