In your example you put the text to be replaced between quotation marks. This should in fact be a regular expression that should be put between two slashes (/regexp/), not a string as in your example. Moreover, if you don't add the "g" flag after the closing slash, the replace function will work only on the first occurrence of the pattern to be replaced. The replacement pattern must always be a string or a variable containing a string.
In my opinion, if you need to replace a variable your code should be something like this
- Code: Select all
var myVar = mySpecialTag;
var myregExp = new RegExp(myVar,"g");
phrase2 = phrase1.replace(myregExp,"replacement string");
If you used a string as replace pattern instead of a variable you should try this (where mySpecialTag must be a string constructed as a a regular expression)
- Code: Select all
phrase2 = phrase1.replace(/mySpecialTag/g,"replacement string");
Please note the "g" flag used as the second argument in the RegExp object construction or after the closing slash in the second example. This tells the replace function to check all the occurrences of the replace pattern