String replace()
syntax: |
string.replace(pattern, replexp) |
where: |
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.
|
return: |
string - the original string with replacements in it made according to pattern and replexp.
|
description: |
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 • $+ • $& • $` • $' • \$ |
see: |
String match(), String search(), Regular expression replacement characters, RegExp object static properties
|
example: |
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; } |