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

JavascriptStringVariablesReplace

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

Well, you can use this:

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

or simply:

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

Solution 2 - Javascript

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 - Javascript

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

Solution 4 - Javascript

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionmonkey blotView Question on Stackoverflow
Solution 1 - JavascriptDerek 朕會功夫View Answer on Stackoverflow
Solution 2 - JavascriptErik ReppenView Answer on Stackoverflow
Solution 3 - JavascriptGOTO 0View Answer on Stackoverflow
Solution 4 - JavascriptMatthewSView Answer on Stackoverflow