replace

  • 版本网址缩略名: JavaScript/Reference/Global_Objects/String/replace
  • 版本标题: replace
  • 版本 id: 40740
  • 创建于:
  • 创建者: ziyunfei
  • 是否是当前版本?
  • 评论 5 words added, 5 words removed

修订内容

 

概述

Returns a new string with some or all matches of a pattern replaced by a replacement.  The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match.

Method of String
Implemented in JavaScript 1.2
ECMAScript Edition ECMAScript 3rd Edition

语法

newstring = str.replace(regexp|substr, newSubStr|function[, {{ Non-standard_inline() }} flags]);

参数

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. A number of special replacement patterns are supported; see the "Specifying a string as a parameter" section below.
function
A function to be invoked to create the new substring (to put in place of the substring received from parameter #1). The arguments supplied to this function are described in the "Specifying a function as a parameter" section below.
flags
{{ non-standard_inline() }}A string specifying a combination of regular expression flags. The use of the flags parameter in the String.replace method is non-standard, use a RegExp object with the corresponding flags.
g
global match
i
ignore case
m
match over multiple lines
y
{{ non-standard_inline() }}
sticky

描述

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

To perform a global search and replace, either include the g switch in the regular expression or if the first parameter is a string, include g in the flags parameter.

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, provided the first argument was a RegExp object.

Specifying a function as a parameter

You can specify a function as the second parameter. In this case, the function will be invoked after the match has been performed. The function's result (return value) will be used as the replacement string. (Note: the above-mentioned special replacement patterns do not apply in this case.) Note that the function will be invoked multiple times for each full match to be replaced if the regular expression in the first parameter is global.

The arguments to the function are as follows:

Possible name Supplied value
str The matched substring. (Corresponds to $& above.)
p1, p2, ... The nth parenthesized submatch string, provided the first argument to replace was a RegExp object. (Correspond to $1, $2, etc. above.)
offset The offset of the matched substring within the total string being examined. (For example, if the total string was "abcd", and the matched substring was "bc", then this argument will be 1.)
s The total string being examined.

(The exact number of arguments will depend on whether the first argument was a RegExp object and, if so, how many parenthesized submatches it specifies.)

The following example will set newString to "abcXXzzzz - XX , zzzzdef":

function replacer(str, p1, p2, offset, s)
{
  return str + " - " + p1 + " , " + p2;
}
var newString = "abcXXzzzzdef".replace(/(X+)(z+)/, replacer);

例子

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'.

var re = /apples/gi;
var str = "Apples are round, and apples are juicy.";
var newstr = str.replace(re, "oranges");
print(newstr);

In this version, a string is used as the first parameter and the global and ignore case flags are specified in the flags parameter.

var str = "Apples are round, and apples are juicy.";
var newstr = str.replace("apples", "oranges", "gi");
print(newstr);

Both of these examples print "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.

var str = "Twas the night before Xmas...";
var newstr = str.replace(/xmas/i, "Christmas");
print(newstr);

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.

var re = /(\w+)\s(\w+)/;
var str = "John Smith";
var newstr = str.replace(re, "$2, $1");
print(newstr);

This prints "Smith, John".

Example: Using an inline function that modifies the matched characters

In this example, all occurrences of capital letters in the string are converted to lower case, and a hyphen is inserted just before the match location. The important thing here is that additional operations are needed on the matched item before it is given back as a replacement.

The replacement function accepts the matched snippet as its parameter, and uses it to transform the case and concatenate the hyphen before returning.

function styleHyphenFormat(propertyName)
{
  function upperToHyphenLower(match)
  {
    return '-' + match.toLowerCase();
  }
  return propertyName.replace(/[A-Z]/g, upperToHyphenLower);
}

Given styleHyphenFormat('borderTop'), this returns 'border-top'.

Because we want to further transform the result of the match before the final substitution is made, we must use a function. This forces the evaluation of the match prior to the toLowerCase() method. If we had tried to do this using the match without a function, the toLowerCase() would have no effect.

var newString = propertyName.replace(/[A-Z]/, '-' + '$&'.toLowerCase());  // won't work

This is because '$&'.toLowerCase() would be evaluated first as a string literal (resulting in the same '$&') before using the characters as a pattern.

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 the function through its second parameter, p1. 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)
{
  function convert(str, p1, offset, s)
  {
    return ((p1-32) * 5/9) + "C";
  }
  var s = String(x);
  var test = /(\d+(?:\.\d*)?)F\b/g;
  return s.replace(test, convert);
}

 

{{ languages( { "es": "es/Referencia_de_JavaScript_1.5/Objetos_globales/String/replace", "fr": "fr/R\u00e9f\u00e9rence_de_JavaScript_1.5_Core/Objets_globaux/String/replace", "ja": "ja/Core_JavaScript_1.5_Reference/Global_Objects/String/replace", "pl": "pl/Dokumentacja_j\u0119zyka_JavaScript_1.5/Obiekty/String/replace","en": "en/JavaScript/Reference/Global_Objects/String/replace" } ) }}

修订版来源

<p> </p>
<h3 name="Summary">概述</h3>
<p>Returns a new string with some or all matches of a <code>pattern</code> replaced by a <code>replacement</code>.  The <code>pattern</code> can be a string or a RegExp, and the <code>replacement</code> can be a string or a function to be called for each match.</p>
<table class="standard-table"> <thead> <tr> <th class="header" colspan="2">Method of <a href="/zh-cn/JavaScript/Reference/Global_Objects/String" title="zh-cn/JavaScript/Reference/Global_Objects/String"><code>String</code></a></th> </tr> </thead> <tbody> <tr> <td>Implemented in</td> <td>JavaScript 1.2</td> </tr> <tr> <td>ECMAScript Edition</td> <td>ECMAScript 3rd Edition</td> </tr> </tbody>
</table>
<h3 name="Syntax">语法</h3>
<p><code><em>newstring</em> = <em>str</em>.replace(<em>regexp|substr</em>, <em>newSubStr|function[</em>, </code>{{ Non-standard_inline() }} <code><em>flags]</em>);</code></p>
<h3 name="Parameters">参数</h3>
<dl> <dt><code>regexp</code></dt> <dd>A <a href="/zh-cn/JavaScript/Reference/Global_Objects/RegExp" title="zh-cn/Core_JavaScript_1.5_Reference/Global_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="/zh-cn/Core_JavaScript_1.5_Reference/Global_Objects/String" title="zh-cn/Core_JavaScript_1.5_Reference/Global_Objects/String">String</a> that is to be replaced by <code>newSubStr</code>.</dd>
</dl>
<dl> <dt><code>newSubStr</code></dt> <dd>The <a href="/zh-cn/Core_JavaScript_1.5_Reference/Global_Objects/String" title="zh-cn/Core_JavaScript_1.5_Reference/Global_Objects/String">String</a> that replaces the substring received from parameter #1. A number of special replacement patterns are supported; see the "Specifying a string as a parameter" section below.</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). The arguments supplied to this function are described in the "Specifying a function as a parameter" section below.</dd>
</dl>
<dl> <dt><code>flags</code></dt> <dd>{{ non-standard_inline() }}A string specifying a combination of regular expression flags. The use of the flags parameter in the String.replace method is non-standard, use a RegExp object with the corresponding flags. <dl> <dt><code>g</code></dt> <dd>global match</dd> <dt><code>i</code></dt> <dd>ignore case</dd> <dt><code>m</code></dt> <dd>match over multiple lines</dd> <dt><code>y</code></dt> <dd>{{ non-standard_inline() }}</dd> <dd>sticky</dd> </dl> </dd>
</dl>
<h3 name="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>To perform a global search and replace, either include the <code>g</code> switch in the regular expression or if the first parameter is a string, include <code>g</code> in the <code>flags</code> parameter.</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 style="white-space: nowrap;"><code>$<em>n</em></code> or <code>$<em>nn</em></code></td> <td> <p>Where <code><em>n</em></code> or <code><em>nn</em></code> are decimal digits, inserts the <em>n</em>th parenthesized submatch string, provided the first argument was a <code>RegExp</code> object.</p> </td> </tr> </tbody>
</table>
<h4 name="Specifying_a_function_as_a_parameter">Specifying a function as a parameter</h4>
<p>You can specify a function as the second parameter. In this case, the function will be invoked after the match has been performed. The function's result (return value) will be used as the replacement string. (Note: the above-mentioned special replacement patterns do <em>not</em> apply in this case.) Note that the function will be invoked multiple times for each full match to be replaced if the regular expression in the first parameter is global.</p>
<p>The arguments to the function are as follows:</p>
<table class="fullwidth-table"> <tbody> <tr> <td class="header">Possible name</td> <td class="header">Supplied value</td> </tr> <tr> <td><code>str</code></td> <td>The matched substring. (Corresponds to $&amp; above.)</td> </tr> <tr> <td><code>p1, p2, ...</code></td> <td>The <em>n</em>th parenthesized submatch string, provided the first argument to <code>replace</code> was a <code>RegExp</code> object. (Correspond to $1, $2, etc. above.)</td> </tr> <tr> <td><code>offset</code></td> <td>The offset of the matched substring within the total string being examined. (For example, if the total string was <code>"abcd"</code>, and the matched substring was <code>"bc"</code>, then this argument will be <code>1</code>.)</td> </tr> <tr> <td style="white-space: nowrap;"><code>s</code></td> <td>The total string being examined.</td> </tr> </tbody>
</table>
<p>(The exact number of arguments will depend on whether the first argument was a <code>RegExp </code>object and, if so, how many parenthesized submatches it specifies.)</p>
<p>The following example will set <code>newString </code>to <code style="white-space: nowrap;">"abcXXzzzz - XX , zzzzdef"</code>:</p>
<pre class="brush: js">function replacer(str, p1, p2, offset, s)
{
  return str + " - " + p1 + " , " + p2;
}
var newString = "abcXXzzzzdef".replace(/(X+)(z+)/, replacer);
</pre>
<h3 name="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 class="brush: js">var re = /apples/gi;
var str = "Apples are round, and apples are juicy.";
var newstr = str.replace(re, "oranges");
print(newstr);
</pre>
<p>In this version, a string is used as the first parameter and the global and ignore case flags are specified in the <code>flags</code> parameter.</p>
<pre class="brush: js">var str = "Apples are round, and apples are juicy.";
var newstr = str.replace("apples", "oranges", "gi");
print(newstr);
</pre>
<p>Both of these examples print "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 class="brush: js">var str = "Twas the night before Xmas...";
var newstr = str.replace(/xmas/i, "Christmas");
print(newstr);
</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 class="brush: js">var re = /(\w+)\s(\w+)/;
var str = "John Smith";
var newstr = str.replace(re, "$2, $1");
print(newstr);
</pre>
<p>This prints "Smith, John".</p>
<h4 name="Example:_Using_an_inline_function_that_modifies_the_matched_characters">Example: Using an inline function that modifies the matched characters</h4>
<p>In this example, all occurrences of capital letters in the string are converted to lower case, and a hyphen is inserted just before the match location. The important thing here is that additional operations are needed on the matched item before it is given back as a replacement.</p>
<p>The replacement function accepts the matched snippet as its parameter, and uses it to transform the case and concatenate the hyphen before returning.</p>
<pre class="brush: js">function styleHyphenFormat(propertyName)
{
  function upperToHyphenLower(match)
  {
    return '-' + match.toLowerCase();
  }
  return propertyName.replace(/[A-Z]/g, upperToHyphenLower);
}
</pre>
<p>Given <code>styleHyphenFormat('borderTop')</code>, this returns 'border-top'.</p>
<p>Because we want to further transform the <em>result</em> of the match before the final substitution is made, we must use a function. This forces the evaluation of the match prior to the <code>toLowerCase()</code> method. If we had tried to do this using the match without a function, the toLowerCase() would have no effect.</p>
<pre class="brush: js">var newString = propertyName.replace(/[A-Z]/, '-' + '$&amp;'.toLowerCase());  // won't work
</pre>
<p>This is because <code>'$&amp;'.toLowerCase()</code> would be evaluated first as a string literal (resulting in the same <code>'$&amp;'</code>) before using the characters as a pattern.</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 the function through its second parameter, <code>p1</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 class="brush: js">function f2c(x)
{
  function convert(str, p1, offset, s)
  {
    return ((p1-32) * 5/9) + "C";
  }
  var s = String(x);
  var test = /(\d+(?:\.\d*)?)F\b/g;
  return s.replace(test, convert);
}
</pre>
<p> </p>
<p>{{ languages( { "es": "es/Referencia_de_JavaScript_1.5/Objetos_globales/String/replace", "fr": "fr/R\u00e9f\u00e9rence_de_JavaScript_1.5_Core/Objets_globaux/String/replace", "ja": "ja/Core_JavaScript_1.5_Reference/Global_Objects/String/replace", "pl": "pl/Dokumentacja_j\u0119zyka_JavaScript_1.5/Obiekty/String/replace","en": "en/JavaScript/Reference/Global_Objects/String/replace" } ) }}</p>
恢复到这个版本