replace

 

概述

使用一个替换值替换掉一个替换模式在原字符串中一个或所有的匹配项,并返回替换后的字符串,这个替换模式可以是字符串或者正则表达式.替换值可以是一个字符串或者是一个函数.

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

语法

newstring = str.replace(regexp|substr, newSubStr|function[, flags]);

参数

regexp
一个 RegExp 对象.该正则所匹配的内容会被第二个参数的返回值替换掉.
substr
替换掉的一个 String.
newSubStr
替换掉第一个参数在原字符串中的匹配部分.该字符串中可以内插一些特殊的变量名.
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
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   全局替换
i   忽略大小写
m   多行模式
y      sticky

描述

该方法并不改变调用它的字符串本身,而只是返回替换后的字符串.

在进行全局的搜索替换时,如果第一个参数是正则表达式.那么使用正则的 g 选项,如果第一个参数是字符串,那么在第三个参数( )中加入 g 选项

使用字符串作为第二个参数

替换字符串可以插入下面的特殊变量名

变量名 代表的值
$$ 表示字符串 "$".
$& 表示第一个参数所匹配的子串
$` 位于匹配子串$&左边的内容.
$' 位于匹配子串$&右边的内容.
$n or $nn

如果n或nn是个十进制的数字,并且replace方法的第一个参数是个正则表达式,那么$n表示正则表达式中的第n个子匹配字符串.

使用函数作为第二个参数

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:

变量名 代表的值
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.)

下面的例子将 newString 替换成 "abcXXzzzz - XX , zzzzdef":

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

例子

Example: 在 replace 中使用正则的 globalignore 选项

下面的例子中,正则表达式包含有全局替换(g)和忽略大小写(i)的选项,这使得replace方法用'oranges'替换掉了所有出现的"apples".

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

和上面的例子比起来,下面的例子中replace方法的第一个参数使用字符串而不是正则表达式.g和i选项只能放在三个参数中.

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

这两个例子都打印出 "oranges are round, and oranges are juicy."

Example: 在 replace方法中使用正则直接量

下面的例子中,replace方法的第一个参数使用正则表达式直接量并且使用了i(忽略大小写)选项

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

打印出 "Twas the night before Christmas..."

Example: 交换字符串中的两个单词

下面的例子演示了如何交换一个字符串中两个单词的位置,第二个参数中内插了特殊变量名$1和$2

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

打印出 "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: 将华氏温度转换为对等的摄氏温度

下面的例子演示如何将华氏温度转换为对等的摄氏温度.华氏温度用一个数字加一个"F"来表示,f2c函数将返回一个数字加"C"来表示的摄氏温度.如果形参x的传入实参为''212F",那么函数将返回'100C',同样,"0F"将转换成为"-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);
}

 

Document Tags and Contributors

Contributors to this page: ziyunfei
最后编辑者: ziyunfei,