Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
112
rated 0 times [  119] [ 7]  / answers: 1 / hits: 79268  / 12 Years ago, fri, april 13, 2012, 12:00:00

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?


More From » string

 Answers
90

Well, you can use this:



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


or simply:



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

[#86265] Thursday, April 12, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
trentb

Total Points: 261
Total Questions: 101
Total Answers: 90

Location: French Southern and Antarctic Lands
Member since Fri, Jan 6, 2023
1 Year ago
;