replace()

The replace() method is used within regular expressions to replace the string that is being matched with an alternate string, when a match is made. For a full explanation of regular expressions and the RegExp object, see the JavaScript Object Reference, RegExp and regular expression. For the use of the replace() method, see the syntax and example below.

syntax:

stringName.replace(regExpName, replacementString)

EXAMPLE

var stringToSearch = new String("This the text to be searched
");



var theRegExp = /This /g;



var replaceString = stringToSearch.replace(theRegExp, "This is ");



document.write("The original text was wrong. The original string was:
" + stringToSearch);



document.write("The word 'is' has been left out. The new string is :
" + replaceString)

The example starts out with the creation of a new string called stringToSearch. The regular expression is then defined, called theRegExp, which searches stringToSearch for the word "This". The /g denotes that the search is to be global in nature. Then comes the replace() method which replaces the word "This" with the words "This is ". The first document.write statement then writes some descriptive text to the screen along with the stringToSearch text, which has the error in it. The next document.write statement then writes some descriptive text to the screen with the new text string, replaceString. The ouput should be as follows:



The original text was wrong. The original string was:

This the text to be searched

The word 'is' has been left out. The new string is :

This is the text to be searched