Replace String Method

The Replace String method uses the regular expression that you define in the pattern argument to search a string. If it finds a match, then it replaces the string it finds with the string that you define in the replexp argument.

Format

stringVar.replace(pattern, replexp)

The following table describes the arguments for the Replace String method.

Argument Description

pattern

Regular expression that this method finds in a string.

replexp

A replacement expression that can include one of the following items:

  • String

  • String that includes regular expression elements
  • Function

Special Characters You Can Use in a Replacement Expression

The following table describes the special characters that you can use in a replacement expression.

Character Description

$1, $2 … $9

The text that the regular expression matches. This text resides in a set of parentheses in the string. For example, $1 replaces the text that the Replace String method matches in the first regular expression it encounters that resides in a set of parentheses.

$+

Same as the $1, $2 … $9 characters, except with the $+ character the replacement occurs in the regular expression that resides in the last set of parentheses.

$&

The text that a regular expression matches.

$`

The text that precedes the text that a regular expression matches.

$'

The text that comes after the text that a regular expression matches.

\$

The dollar sign character.

Example

The following example includes the Replace String method:

var rtn;

var str = "one two three two one";

var pat = /(two)/g;
// rtn == "one zzz three zzz one"

rtn = str.replace(pat, "zzz");
// rtn == "one twozzz three twozzz one";

rtn = str.replace(pat, "$1zzz");
// rtn == "one 5 three 5 one"

rtn = str.replace(pat, five());
// rtn == "one twotwo three twotwo one";

rtn = str.replace(pat, "$&$&”);
function five()
{

   return 5;
}