JavaScript tutorial:
replace method 

 

Applies to: String Object

The replace method returns a copy of a string with text replaced using a regular expression.

Syntax

stringObj.replace(rgExp, replaceText)

The replace method syntax has these parts:

Part

Description

stringObj

Required. The String object or literal on which to perform the replace. This object is not modified by the replace method.

rgExp

Required. A Regular Expression object describing what to search for.

replaceText

Required. A String object or literal containing the text to replace for every successful match of rgExp in stringObj.

Return value

The replace method returns a copy of a string with text replaced using a regular expression.

Example

The result of the replace method is a copy of stringObj after all replacements have been made.

The method updates the contents of the RegExp object.

The following example illustrates the use of the replace method:

function replaceString(str,oldstr, newstr)
{
var r, re;
re = new RegExp(oldstr);
r = str.replace(re, newstr);
return(r);
}document.write(replaceString("The quick brown fox jumped over the lazy yellow dog.","fox", "pig"));

To run the code, paste it into JavaScript Editor, and click the Execute button.

See also: exec method, match method, RegExp Object, search method, String Object methods, test method