Symbol.replace接受一个字符串类型的参数和一个替换用的字符串,最终依然返回一个字符串。该函数会在执行String.prototype.replace()
方法时被调用。
The Symbol.replace well-known symbol specifies the method that replaces matched substrings of a string. This function is called by the String.prototype.replace() method.
首先来学习一下String.prototype.replace
。该方法接收两个参数,一个pattern用于查找字符串,而replacement用于替换被查找的字符串。
比如
const p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?';
console.log(p.replace('dog', 'monkey'));
// expected output: "The quick brown fox jumps over the lazy monkey. If the dog reacted, was it really lazy?"
这里pattern和replacement都是普通的字符串,执行之后会将段落中的dog更换为monkey。但是如果想把段落中的dog无论大小写都查找出来替换,则需要使用正则表达式,如下所示
const p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?';
const regex = /Dog/gi;
console.log(p.replace(regex, 'ferret'));
// expected output: "The quick brown fox jumps over the lazy ferret. If the ferret reacted, was it really lazy?"
在这里pattern是一个正则表达式,然后使用g和i符号来进行全局不区分大小写匹配,然后更换为replacement指定的值’ferret’。
进行正则表达式匹配时,还可以使用到捕获组
// Switching words in a string
const re = /(\w+)\s(\w+)/;
const str = 'Maria Cruz';
const newstr = str.replace(re, '$2, $1');
console.log(newstr); // Cruz, Maria
另外,replacement不仅仅可以是字符串,而且可以是函数 。如果为函数时,会在每次匹配时根据函数返回值替换匹配的值。比如执行以下的styleHyphenFormat函数会将字符串中的大小字母进行替换。如果大小字母在最前面,就仅仅替换为小写,否则还在前面加上一个-
符号。
// Using an inline function that modifies the matched characters
// 将大小字母转为 如果在首位则转为小写字母 否则转为 -和小写字母
function styleHyphenFormat(propertyName) {
// The replacement function accepts the matched snippet as its parameter,
// and uses it to transform the case and concatenate the hyphen before returning.
function upperToHyphenLower(match, offset, string) {
return (offset > 0 ? '-' : '') + match.toLowerCase();
}
return propertyName.replace(/[A-Z]/g, upperToHyphenLower);
}
//border-top
console.log(styleHyphenFormat('borderTop'));
更详细的内容参考:String.prototype.replace()
在上面已经介绍了pattern可以为字符串和正则表达式,在ES6中,pattern也可以是一个拥有Symbol.replace
方法的任意对象。比如
class Replace1 {
constructor(value) {
this.value = value;
}
[Symbol.replace](string) {
return `s/${string}/${this.value}/g`;
}
}
// expected output: "s/foo/bar/g"
console.log('foo'.replace(new Replace1('bar')));
class CustomReplacer {
constructor(value) {
this.value = value;
}
[Symbol.replace](string) {
return string.replace(this.value, "#!@?");
}
}
// "#!@?tball"
console.log("football".replace(new CustomReplacer("foo")));