contents   index   previous   next

String replace()


string.replace(pattern, replexp)


pattern - a regular expression pattern to find or match in string.


replexp - a replacement expression which may be a string, a string with regular expression elements, or a function.



string - the original string with replacements in it made according to pattern and replexp.



This string is searched using the regular expression pattern defined by pattern. If a match is found, it is replaced by the substring defined by replexp. The parameter replexp may be a:


• a simple string

• a string with special regular expression replacement elements in it

• a function that returns a value that may be converted into a string

If any replacements are done, appropriate RegExp object static properties, such as RegExp.leftContext, RegExp.rightContext, RegExp.$n, and so forth are set, providing more information about the replacements.


The special characters that may be in a replacement expression are (see regular expression replacement characters):


$1, $2 ... $9
The text that is matched by regular expression patterns inside of parentheses. For example, $1 will put the text matched in the first parenthesized group in a regular expression pattern. See (...) under regular expression reference characters.

The text that is matched by the last regular expression pattern inside of the last parentheses, that is, the last group.

The text that is matched by a regular expression pattern.

The text to the left of the text matched by a regular expression pattern.

The text to the right of the text matched by a regular expression pattern.

The dollar sign character.


String match(), String search(), Regular expression replacement characters, RegExp object static properties



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;



String search()