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


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


一个 RegExp 对象.该正则所匹配的内容会被第二个参数的返回值替换掉.
替换掉的一个 String.
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.
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



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 选项


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


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

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

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


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

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

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


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

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


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,