ES6之Symbol.replace


ES6学习系列 😃


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"))); 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lang20150928

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值