For example, if I had the following string:
And I wanted to replace the word "red" with "dark red", the result should be:
However, I'd like to substitute "dark red" with any arbitrary string stored in a variable.
One of the simplest ways to do this is to use the regular expression constructor combined with the 'replace' function. The easiest way to show this is by an example:
var replaceThis = "red";
var replaceWith = "dark red";
var theString = "The red strawberries fell off the red table.";
var theNewString =
theString.replace(new RegExp(replaceThis, "g"), replaceWith);
However, regular expressions cannot be passed simply as strings, therefore passing "/red/g" or a variable containing that string as the first parameter of replace would have been interpreted as the string "/red/g" rather than the regular expression /red/g. This problem is worked around by converting the string of the regular expression to a valid regular expression via the regular expression constructor.
Additional details can be found at the following references: