replace

  • Enlace amigable (slug) de la revisión: Referencia_de_JavaScript_1.5/Objetos_globales/String/replace
  • Título de la revisión: replace
  • Id de la revisión: 181340
  • Creada:
  • Creador: Talisker
  • ¿Es la revisión actual? No
  • Comentario New page: <breadcrumbs></breadcrumbs> == Resumen == Finds a match between a regular expression and a string, and replaces the matched substring with a new substring. <table class="fullwidth-table...

Contenido de la revisión

Resumen

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

Método de String
Implementado en: JavaScript 1.2

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

Versión ECMA: ECMA-262

Sintaxis

var newString = str.replace(regexp/substr, newSubStr/function[, flags]);

Parámetros

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).
flags 
(SpiderMonkey extension) A String containing any combination of the RegExp flags: g - global match, i - ignore case, m - match over multiple lines. This parameter is only used if the first parameter is a string.

Descripción

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 flag in the regular expression or if the first parameter is a string, include g in the flags parameter.

Especificando una cadena como un parámetro

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.

Especificando una función con un parámetro

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. If the first argument was a RegExp object, then 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 XXzzzz - XX , zzzz.

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

Ejemplos

Ejemplo: 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."

Ejemplo: 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..."

Ejemplo: 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".

Ejemplo: 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]/, 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.

Ejemplo: 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);
}
{{ wiki.languages( { "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" } ) }}

Fuente de la revisión

<p>
</p>
<h3 name="Resumen"> Resumen </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">Método de <a href="es/Referencia_de_JavaScript_1.5/Objetos_globales/String">String</a></td>
</tr>
<tr>
<td>Implementado en:</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>Versión ECMA:</td>
<td>ECMA-262</td>
</tr>
</tbody></table>
<h3 name="Sintaxis"> Sintaxis </h3>
<pre class="eval">var newString = <i>str</i>.replace(<i>regexp</i>/<i>substr</i>, <i>newSubStr</i>/<i>function</i>[, <i>flags</i>]);
</pre>
<h3 name="Par.C3.A1metros"> Parámetros </h3>
<dl><dt> <code>regexp</code> </dt><dd> A <a href="es/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="es/Core_JavaScript_1.5_Reference/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="es/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>
<dl><dt> <code>flags</code> </dt><dd> <i>(<a href="es/SpiderMonkey">SpiderMonkey</a> extension)</i> A <a href="es/Core_JavaScript_1.5_Reference/Objects/String"> String</a> containing any combination of the RegExp flags: <code>g</code> - global match, <code>i</code> - ignore case, <code>m</code> - match over multiple lines. This parameter is only used if the first parameter is a string.
</dd></dl>
<h3 name="Descripci.C3.B3n"> Descripción </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> flag 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="Especificando_una_cadena_como_un_par.C3.A1metro"> Especificando una cadena como un parámetro </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>$<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, provided the first argument was a <code>RegExp</code> object.</td>
</tr>
</tbody></table>
<h4 name="Especificando_una_funci.C3.B3n_con_un_par.C3.A1metro"> Especificando una función con un parámetro </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. If the first argument was a <code>RegExp</code> object, then 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 XXzzzz - XX , zzzz.
</p>
<pre class="eval">function replacer(str, p1, p2, offset, s)
{
  return str + " - " + p1 + " , " + p2;
}
var newString = "XXzzzz".replace(/(X*)(z*)/, replacer);
</pre>
<h3 name="Ejemplos"> Ejemplos </h3>
<h4 name="Ejemplo:_Using_global_and_ignore_with_replace"> Ejemplo: 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="eval">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="eval">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="Ejemplo:_Defining_the_regular_expression_in_replace"> Ejemplo: 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="eval">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="Ejemplo:_Switching_words_in_a_string"> Ejemplo: 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="eval">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="Ejemplo:_Using_an_inline_function_that_modifies_the_matched_characters"> Ejemplo: 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="eval">function styleHyphenFormat(propertyName)
{
  function upperToHyphenLower(match)
  {
    return '-' + match.toLowerCase();
  }
  return propertyName.replace(/[A-Z]/, upperToHyphenLower);
}
</pre>
<p>Given <code>styleHyphenFormat('borderTop')</code>, this returns 'border-top'.
</p><p>Because we want to further transform the <i>result</i> 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="eval">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="Ejemplo:_Replacing_a_Fahrenheit_degree_with_its_Celsius_equivalent"> Ejemplo: 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="eval">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>
<div class="noinclude">
</div>
{{ wiki.languages( { "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" } ) }}
Revertir a esta revisión