• Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

1. Strings > 1.7. Searching and Replacing Substrings

Searching and Replacing Substrings

NN 4, IE 4

Problem

You want to perform a global search-and-replace operation on a text string.

Solution

The most efficient way (for NN 4 or later and IE 4 or later) is to use a regular expression with the replace( ) method of the String object:

var re = /a string literal/g;
var result = mainString.replace(re, replacementString);

Invoking the replace( ) method on a string does not change the source string. Capture the changed string returned by the method, and apply the result where needed in your scripts or page. If no replacements are made, the original string is returned by the method. Be sure to specify the g modifier for the regular expression to force the replace( ) method to operate globally on the original string; otherwise, only the first instance is replaced.


PREVIEW

                                                                          

Not a subscriber?

Start A Free Trial


  
  • Creative Edge
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint