Saturday, 6 October 2012

Replace every instance of a word in a string with a word stored in a variable using javascript


In javascript, I'd like to replace every instance of a word (or substring) in a longer string, with a string stored in a variable.

For example, if I had the following string:

The red strawberries fell off the red table.

And I wanted to replace the word "red" with "dark red", the result should be:

The dark red strawberries fell off the dark red table.

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

More details:

Using the 'replace' function is a simple way to replace something in a string. Unfortunately, if you want to replace more than one instance of a substring in a string, passing two strings as parameters to the 'replace' function, such as in "str.replace('this', 'that')", will not work because the function will simply replace only the first match. In the highlighted example above, only the first instance of 'red' would have been replaced with 'dark red'. To get around this issue, the first parameter should be a regular expression, with the desired search string being 'red' and the modifier being 'g' for global matching. In javascript, this regular expression would look like: /red/g

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:

No comments:

Post a Comment