1. Home
  2. Computing & Technology
  3. JavaScript

Regular Expressions

3. Replacing Matches

clr gif

The replace method available on string objects can be used to substitute one value for another in any text string. While this method can use ordinary text strings for both the text to find and the text to replace it with the method is far more powerful when you use regular expressions in place of one or both of the text strings.

With plain text the method will locate the first occurrence of the find text in the first parameter and replace it with the replace text in the second parameter. Even using what we already know about regular expressions we can use a regular expression in place of the first text string to get the find of the string to ignore capitalization or to find and replace all occurrences. For example:

var myString = 'The boy sat on the log next to the tree.';
var re = /the/g;
myString = myString.replace(re,'a');

In this example, myString is searched globally for all occurrences of the and each of those occurrences is replaced by a. Since we are not ignoring capitalization the text in the example after the replace reads 'The boy sat on a log next to a tree.' Had we told the regular expression to ignore capitalization as well as processing globally then the text would have been changed to 'a boy sat on a log next to a tree.'

Explore JavaScript
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. JavaScript

©2009 About.com, a part of The New York Times Company.

All rights reserved.