Esta tradução está incompleta. Ajude atraduzir este artigo.
Resumo
O método replace()
retorna uma nova string com algum ou todas as combinações do padrão substituído por um substituto. O padrão pode ser uma string ou uma RegExp
, e o substituto pode ser uma string ou uma função a ser chamada por cada combinação.
Sintaxe
str.replace(regexp|substr, newSubStr|function[, flags])
Parâmetros
regexp
- Um objeto
RegExp
. a combinação é substituída pelo valor retornado do parâmetro #2. substr
- Uma
String
que é para ser substituída pelanewSubStr
. newSubStr
- A
String
que substitui a substring recebida do parâmetro #1. Uma série de padrões de substituições especiais são suportados; veja a seção "Especificando uma string como parâmetro" abaixo. 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
-
Nota: O argumento
flags
não funciona no v8 Core (Chrome e NodeJs). Uma string especificando uma combinação de flags de expressão regular. O uso do parâmetroflags
no métodoString.prototype.replace()
é não-padrão. Ao invés de usar este parâmetro, use um objetoRegExp
com a flags correspondente. O valor deste parâmetro se for utilizado deve ser uma string consistindo de um ou mais dos seguintes caracteres para afetar a operação, tais como descrito:g
- combinação global
i
- ignorar caso
m
- combinação em várias linhas
y
- sticky
Retornos
Uma nova string com algum ou todas as combinações do padrão substituído pelo substituidor.
Descrição
Este método não muda o objeto String
. Ele simplesmente retorna uma nova string.
Para realizar uma pesquisa global e substituir, incluir a chave g
na expressão regular ou se o primeiro parâmetro é uma string, inclua g
no parâmetro flags.
Especificando uma string como parâmetro
A string substituidora pode incluir o seguinte padrão de substituição especial:
Pattern | Inserts |
$$ |
Insere um "$". |
$& |
Insere a string casada. |
$` |
Insere a porção da string que precede a substring combinada. |
$' |
Insere a porção da string que segue a substring combinada. |
$n ou $nn |
Onde n ou nn são dígitos decimais, insere a n-ésima substring entre parêntesis casada, dado que o primeiro argumento foi um objeto RegExp . |
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 |
match |
The matched substring. (Corresponds to $& above.) |
p1, p2, ... |
The nth parenthesized submatch string, provided the first argument to replace() was a RegExp object. (Corresponds to $1 , $2 , etc. above.) For example, if /(\a+)(\b+)/ , was given, p1 is the match for \a+ , and p2 for \b+ . |
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.) |
string |
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 'abc - 12345 - #$*%'
:
function replacer(match, p1, p2, p3, offset, string) { // p1 is nondigits, p2 digits, and p3 non-alphanumerics return [p1, p2, p3].join(' - '); } var newString = 'abc12345#$*%'.replace(/([^\d]*)(\d*)([^\w]*)/, replacer);
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'.
var re = /apples/gi; var str = 'Apples are round, and apples are juicy.'; var newstr = str.replace(re, 'oranges'); console.log(newstr);
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'); console.log(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'); console.log(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]/g, '-' + '$&'.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); }
Example: Use an inline function with a regular expression to avoid for
loops
The following example takes a string pattern and converts it into an array of objects.
Input:
A string made out of the characters x
, -
and _
x-x_ x---x---x---x--- x-xxx-xx-x- x_x_x___x___x___
Output:
An array of objects. An 'x'
denotes an 'on'
state, a '-'
(hyphen) denotes an 'off'
state and an '_'
(underscore) denotes the length of an 'on'
state.
[ { on: true, length: 1 }, { on: false, length: 1 }, { on: true, length: 2 } ... ]
Snippet:
var str = 'x-x_'; var retArr = []; str.replace(/(x_*)|(-)/g, function(match, p1, p2) { if (p1) { retArr.push({ on: true, length: p1.length }); } if (p2) { retArr.push({ on: false, length: 1 }); } }); console.log(retArr);
This snippet generates an array of 3 objects in the desired format without using a for
loop.
Specifications
Specification | Status | Comment |
---|---|---|
ECMAScript 3rd Edition. | Standard | Initial definition. Implemented in JavaScript 1.2. |
ECMAScript 5.1 (ECMA-262) The definition of 'String.prototype.replace' in that specification. |
Standard | |
ECMAScript 6 (ECMA-262) The definition of 'String.prototype.replace' in that specification. |
Release Candidate |
Browser compatibility
Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|
Basic support | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) |
Feature | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|---|
Basic support | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) |
Firefox-specific notes
- Starting with Gecko 27 (Firefox 27 / Thunderbird 27 / SeaMonkey 2.24), this method has been adjusted to conform with the ECMAScript specification. When
replace()
is called with a global regular expression, theRegExp.lastIndex
property (if specified) will be reset to0
(bug 501739).