String.prototype.replace()

  • Revision slug: JavaScript/Reference/Global_Objects/String/replace
  • Revision title: replace
  • Revision id: 42307
  • Created:
  • Creator: Mgjbot
  • Is current revision? No
  • Comment robot Adding: pl

Revision Content

Summary

Finds a match between a regular expression and a string, and replaces the matched substring with a new substring.

Method of String
Implemented in: JavaScript 1.2

JavaScript 1.3: Added the ability to specify a function as the second parameter.

ECMA Version: ECMA-262

Syntax

replace(regexp/substr, newSubStr/function)

Versions prior to JavaScript 1.3

replace(regexp, newSubStr)

Parameters

regexp 
A RegExp object. The match is replaced by the return value of parameter #2.
substr 
A String that is to be replaced by newSubStr.
newSubStr 
The String that replaces the substring received from parameter #1.
function 
A function to be invoked to create the new substring (to put in place of the substring received from parameter #1).

Description

This method does not change the String object it is called on. It simply returns a new string.

If you want to execute a global search and replace, include the g flag in the regular expression.

Specifying a string as a parameter

The replacement string can include the following special replacement patterns:

Pattern Inserts
$$ Inserts a "$".
$& Inserts the matched substring.
$` Inserts the portion of the string that precedes the matched substring.
Inserts the portion of the string that follows the matched substring.
$n or $nn Where n or nn are decimal digits, inserts the nth parenthesized submatch string.

Specifying a function as a parameter

When you specify a function as the second parameter, the function is invoked after the match has been performed. (The use of a function in this manner is often called a lambda expression.)

In your function, you can dynamically generate the string that replaces the matched substring. The result of the function call is used as the replacement value.

The nested function can use the matched substrings to determine the new string (newSubStr) that replaces the found substring. You get the matched substrings through the parameters of your function. The first parameter of your function holds the complete matched substring. The following n parameters can be used for parenthetical matches, remembered submatch strings, where n is the number of submatch strings in the regular expression. Finally, the last two parameters are the offset within the string where the match occurred and the string itself. For example, the following replace method returns XX.zzzz - XX , zzzz.

"XXzzzz".replace(/(X*)(z*)/,
                   function (str, p1, p2, offset, s) {
                      return str + " - " + p1 + " , " + p2;
                   }
                )

Backward Compatibility

JavaScript 1.2

You cannot specify a function as the second parameter.

Examples

Example: Using global and ignore with replace

In the following example, the regular expression includes the global and ignore case flags which permits replace to replace each occurrence of 'apples' in the string with 'oranges'.

<SCRIPT>
re = /apples/gi;
str = "Apples are round, and apples are juicy.";
newstr=str.replace(re, "oranges");
document.write(newstr)
</SCRIPT>

This prints "oranges are round, and oranges are juicy."

Example: Defining the regular expression in replace

In the following example, the regular expression is defined in replace and includes the ignore case flag.

<SCRIPT>
str = "Twas the night before Xmas...";
newstr=str.replace(/xmas/i, "Christmas");
document.write(newstr)
</SCRIPT>

This prints "Twas the night before Christmas..."

Example: Switching words in a string

The following script switches the words in the string. For the replacement text, the script uses the $1 and $2 replacement patterns.

<SCRIPT LANGUAGE="JavaScript1.2">
re = /(\w+)\s(\w+)/;
str = "John Smith";
newstr = str.replace(re, "$2, $1");
document.write(newstr)
</SCRIPT>

This prints "Smith, John".

Example: Replacing a Fahrenheit degree with its Celsius equivalent

The following example replaces a Fahrenheit degree with its equivalent Celsius degree. The Fahrenheit degree should be a number ending with F. The function returns the Celsius number ending with C. For example, if the input number is 212F, the function returns 100C. If the number is 0F, the function returns -17.77777777777778C.

The regular expression test checks for any number that ends with F. The number of Fahrenheit degree is accessible to your function through the parameter $1. The function sets the Celsius number based on the Fahrenheit degree passed in a string to the f2c function. f2c then returns the Celsius number. This function approximates Perl's s///e flag.

function f2c(x) {
   var s = String(x)
   var test = /(\d+(?:\.\d*)?)F\b/g
   return s.replace
      (test,
         function (str,p1,offset,s) {
            return ((p1-32) * 5/9) + "C";
         }
      )
}
{{ wiki.languages( { "pl": "pl/Dokumentacja_j\u0119zyka_JavaScript_1.5/Obiekty/String/replace" } ) }}

Revision Source

<p>
</p>
<h3 name="Summary"> Summary </h3>
<p>Finds a match between a regular expression and a string, and replaces the matched substring with a new substring.
</p>
<table class="fullwidth-table">
<tbody><tr>
<td class="header" colspan="2">Method of <a href="en/Core_JavaScript_1.5_Reference/Objects/String">String</a></td>
</tr>
<tr>
<td>Implemented in:</td>
<td>JavaScript 1.2
<p>JavaScript 1.3: Added the ability to specify a function as the second parameter.
</p>
</td>
</tr>
<tr>
<td>ECMA Version:</td>
<td>ECMA-262</td>
</tr>
</tbody></table>
<h3 name="Syntax"> Syntax </h3>
<p><code>
replace(<i>regexp</i>/<i>substr</i>, <i>newSubStr</i>/<i>function</i>)<br>
</code>
</p>
<h4 name="Versions_prior_to_JavaScript_1.3"> Versions prior to JavaScript 1.3 </h4>
<p><code>
replace(<i>regexp</i>, <i>newSubStr</i>)
</code>
</p>
<h3 name="Parameters"> Parameters </h3>
<dl><dt> <code>regexp</code> </dt><dd> A <a href="en/Core_JavaScript_1.5_Reference/Objects/RegExp"> RegExp</a> object. The match is replaced by the return value of parameter #2.
</dd></dl>
<dl><dt> <code>substr</code> </dt><dd> A <a href="en/Core_JavaScript_1.5_Reference/Objects/String"> String</a> that is to be replaced by newSubStr.
</dd></dl>
<dl><dt> <code>newSubStr</code> </dt><dd> The <a href="en/Core_JavaScript_1.5_Reference/Objects/String"> String</a> that replaces the substring received from parameter #1.  
</dd></dl>
<dl><dt> <code>function</code> </dt><dd> A function to be invoked to create the new substring (to put in place of the substring received from parameter #1).
</dd></dl>
<h3 name="Description"> Description </h3>
<p>This method does not change the <code>String</code> object it is called on. It simply returns a new string.
</p><p>If you want to execute a global search and replace, include the <code>g</code> flag in the regular expression.
</p>
<h4 name="Specifying_a_string_as_a_parameter"> Specifying a string as a parameter </h4>
<p>The replacement string can include the following special replacement patterns: 
</p>
<table class="fullwidth-table">
<tbody><tr>
<td class="header">Pattern</td>
<td class="header">Inserts</td>
</tr>
<tr>
<td><code>$$</code></td>
<td>Inserts a "$".</td>
</tr>
<tr>
<td><code>$&amp;</code></td>
<td>Inserts the matched substring.</td>
</tr>
<tr>
<td><code>$`</code></td>
<td>Inserts the portion of the string that precedes the matched substring.</td>
</tr>
<tr>
<td><code>$´</code></td>
<td>Inserts the portion of the string that follows the matched substring.</td>
</tr>
<tr>
<td><code>$<i>n</i></code> or <code>$<i>nn</i></code></td>
<td>Where <code><i>n</i></code> or <code><i>nn</i></code> are decimal digits, inserts the <i>n</i>th parenthesized submatch string.</td>
</tr>
</tbody></table>
<h4 name="Specifying_a_function_as_a_parameter"> Specifying a function as a parameter </h4>
<p>When you specify a function as the second parameter, the function is invoked after the match has been performed. (The use of a function in this manner is often called a lambda expression.)
</p><p>In your function, you can dynamically generate the string that replaces the matched substring. The result of the function call is used as the replacement value.
</p><p>The nested function can use the matched substrings to determine the new string (<code>newSubStr</code>) that replaces the found substring. You get the matched substrings through the parameters of your function. The first parameter of your function holds the complete matched substring. The following <i>n</i> parameters can be used for parenthetical matches, remembered submatch strings, where <i>n</i> is the number of submatch strings in the regular expression. Finally, the last two parameters are the offset within the string where the match occurred and the string itself. For example, the following <code>replace</code> method returns XX.zzzz - XX , zzzz.
</p>
<pre>"XXzzzz".replace(/(X*)(z*)/,
                   function (str, p1, p2, offset, s) {
                      return str + " - " + p1 + " , " + p2;
                   }
                )
</pre>
<h3 name="Backward_Compatibility"> Backward Compatibility </h3>
<h4 name="JavaScript_1.2"> JavaScript 1.2 </h4>
<p>You cannot specify a function as the second parameter.
</p>
<h3 name="Examples"> Examples </h3>
<h4 name="Example:_Using_global_and_ignore_with_replace"> Example: Using <code>global</code> and <code>ignore</code> with <code>replace</code> </h4>
<p>In the following example, the regular expression includes the global and ignore case flags which permits <code>replace</code> to replace each occurrence of 'apples' in the string with 'oranges'.
</p>
<pre>&lt;SCRIPT&gt;
re = /apples/gi;
str = "Apples are round, and apples are juicy.";
newstr=str.replace(re, "oranges");
document.write(newstr)
&lt;/SCRIPT&gt;
</pre>
<p>This prints "oranges are round, and oranges are juicy."
</p>
<h4 name="Example:_Defining_the_regular_expression_in_replace"> Example: Defining the regular expression in <code>replace</code> </h4>
<p>In the following example, the regular expression is defined in <code>replace</code> and includes the ignore case flag.
</p>
<pre>&lt;SCRIPT&gt;
str = "Twas the night before Xmas...";
newstr=str.replace(/xmas/i, "Christmas");
document.write(newstr)
&lt;/SCRIPT&gt;
</pre>
<p>This prints "Twas the night before Christmas..."
</p>
<h4 name="Example:_Switching_words_in_a_string"> Example: Switching words in a string </h4>
<p>The following script switches the words in the string. For the replacement text, the script uses the <code>$1</code> and <code>$2</code> replacement patterns.
</p>
<pre>&lt;SCRIPT LANGUAGE="JavaScript1.2"&gt;
re = /(\w+)\s(\w+)/;
str = "John Smith";
newstr = str.replace(re, "$2, $1");
document.write(newstr)
&lt;/SCRIPT&gt;
</pre>
<p>This prints "Smith, John".
</p>
<h4 name="Example:_Replacing_a_Fahrenheit_degree_with_its_Celsius_equivalent"> Example: Replacing a Fahrenheit degree with its Celsius equivalent </h4>
<p>The following example replaces a Fahrenheit degree with its equivalent Celsius degree. The Fahrenheit degree should be a number ending with F. The function returns the Celsius number ending with C. For example, if the input number is 212F, the function returns 100C. If the number is 0F, the function returns -17.77777777777778C.
</p><p>The regular expression <code>test</code> checks for any number that ends with F. The number of Fahrenheit degree is accessible to your function through the parameter <code>$1</code>. The function sets the Celsius number based on the Fahrenheit degree passed in a string to the <code>f2c</code> function. <code>f2c</code> then returns the Celsius number. This function approximates Perl's s///e flag.
</p>
<pre>function f2c(x) {
   var s = String(x)
   var test = /(\d+(?:\.\d*)?)F\b/g
   return s.replace
      (test,
         function (str,p1,offset,s) {
            return ((p1-32) * 5/9) + "C";
         }
      )
}
</pre>
{{ wiki.languages( { "pl": "pl/Dokumentacja_j\u0119zyka_JavaScript_1.5/Obiekty/String/replace" } ) }}
Revert to this revision