JavaScript参考手册
RegExp
regExp.@@replace
[@@replace]()
方法会在一个字符串中用给定的替换器,替换所有符合正则模式的匹配项,并返回替换后的新字符串结果。用来替换的参数可以是一个字符串或是一个针对每次匹配的回调函数。
语法
regexp[Symbol.replace](str, newSubStr|function)
参数
str
正则替换的目标字符串。newSubStr (replacement)
类型为String
的替换器。支持大多数特殊的替换匹配模式; 见String.prototype.replace()
页的Specifying a string as a parameter部分。function (replacement)
生成新的子字符串的回调函数替换器。作用于该函数的参数的详细描述见String.prototype.replace()
页的 Specifying a function as a parameter部分。
返回值
用替换器替换相应匹配项后的新字符串。
描述
如果匹配模式也是RegExp
对象,这个方法在String.prototype.replace()
的内部调用。例如,下面的两个方法返回相同结果。
'abc'.replace(/a/, 'A');
/a/[Symbol.replace]('abc', 'A');
该方法是为了在RegExp子类中自定义匹配的替换模式。
如果匹配模式不是一个RegExp
对象,String.prototype.replace()
就不会调用该方法,也不会创建一个RegExp
对象。
示例
直接调用
这个方法基本可以和 String.prototype.replace()
一样使用, 不同之处是this
和参数顺序。
var re = /-/g;
var str = '2016-01-01';
var newstr = re[Symbol.replace](str, '.');
console.log(newstr); // 2016.01.01
在子类中使用@@replace
RegExp
的子类可以覆写[@@replace]()
方法来修改默认行为。
class MyRegExp extends RegExp {
constructor(pattern, flags, count) {
super(pattern, flags);
this.count = count;
}
[Symbol.replace](str, replacement) {
// Perform @@replace |count| times.
var result = str;
for (var i = 0; i < this.count; i++) {
result = RegExp.prototype[Symbol.replace].call(this, result, replacement);
}
return result;
}
}
var re = new MyRegExp('\\d', '', 3);
var str = '01234567';
var newstr = str.replace(re, '#'); // String.prototype.replace calls re[@@replace].
console.log(newstr); // ###34567
规范
Specification |
Status |
Comment |
---|---|---|
ECMAScript 2015 (6th Edition, ECMA-262)The definition of 'RegExp.prototype@@replace' in that specification. |
Standard |
Initial definition. |
ECMAScript 2017 Draft (ECMA-262)The definition of 'RegExp.prototype@@replace' in that specification. |
Draft |
|
浏览器兼容性
Feature |
Chrome |
Firefox (Gecko) |
Internet Explorer |
Opera |
Safari |
---|---|---|---|---|---|
Basic support |
? |
49 (49) |
? |
? |
? |
Feature |
Android |
Chrome for Android |
Firefox Mobile (Gecko) |
IE Mobile |
Opera Mobile |
Safari Mobile |
---|---|---|---|---|---|---|
Basic support |
? |
? |
49.0 (49) |
? |
? |
? |
RegExp相关
JavaScript 是一种高级编程语言,通过解释执行,是一门动态类型,面向对象(基于原型)的解释型语言。它已经由ECMA(欧洲电脑制造商协会)通过 ECMAScript 实现语言的标准化。它被世界上的绝大多数网站所使用,也被世界主流浏览器( Chrome、IE、FireFox、Safari、Opera )支持。JavaScript 是一门基于原型、函数先行的语言,是一门多范式的语言,它支持面向对象编程,命令式编程,以及函数式编程。它提供语法来操控文本、数组、日期以及正则表达式等,不支持 I/O,比如网络