Availability
JavaScript 1.2; JScript 3.0; ECMAScript v3
Synopsis
string.replace(regexp, replacement)Arguments
regexp
The RegExp object that specifies the pattern to be replaced. If this
argument is a string, it is used as a literal text pattern to be
searched for; it is not first converted to a RegExp object.
replacement
A string that specifies the replacement text, or a function that is
invoked to generate the replacement text. See the
Section section for details.
Returns
A new string, with the first match, or all matches, of
regexp replaced with
replacement.
Description
replace( ) performs a
search-and-replace operation on
string. It searches
string for one or more substrings that
match regexp and replaces them with
replacement. If
regexp has the global g
attribute specified, replace( ) replaces all
matching substrings. Otherwise, it replaces only the first matching
substring.
replacement may be a string or a function.
If it is a string, each match is replaced by the string. Except,
however, that the $ character has special meaning within
the replacement string. As shown in the
following table, it indicates that a string derived from the pattern
match is to be used in the replacement.
Characters | Replacement |
---|---|
$1, $2, ... $99 | The text that matched the 1st through 99th parenthesized subexpression within regexp |
$& | The substring that matched regexp |
$` | The text to the left of the matched substring |
$' | The text to the right of the matched substring |
$$ | A literal dollar sign |
replacement argument to replace(
) may be a function instead of a string, and this feature
is implemented in JavaScript 1.2 and JScript 5.5. In this case, the
function is invoked for each match and the string it returns is used
as the replacement text. The first argument to the function is the
string that matched the pattern. The next arguments are the strings
that matched any parenthesized subexpressions within the pattern.
There may be zero or more of these arguments. The next argument is an
integer that specifies the position within
string at which the match occurred, and
the final argument to the replacement
function is string itself.
Example
To ensure that the capitalization of the word
"JavaScript" is correct:
text.replace(/javascript/i, "JavaScript");
To convert a single name from "Doe, John" format to
"John Doe" format:
name.replace(/(\w+)\s*,\s*(\w+)/, "$2 $1");
To replace all double quotes with double back and forward single
quotes:
text.replace(/"([^"]*)"/g, "``$1''");
To capitalize the first letter of all words in a string:
text.replace(/\b\w+\b/g, function(word) {
return word.substring(0,1).toUpperCase( ) +
word.substring(1);
});
See Also
RegExp, RegExp.exec( ), RegExp.test( ), String.match( ),
String.search( ); Chapter 10