js 如何全部替代一个子串为另一个子串

2020-07-02 00:00:00 专区 订阅 代码 可以使用 复制

本题摘自于我 github 上的面试每日一题:github.com/shfshanyue/…,并有大厂面经及内推信息

如果需要全量替换字符串,可以使用 String.prototype.replace(re, replacer),其中正则表达式需要开启 global flag

const s = 'foo foo foo'
s.replce(/foo/g, 'bar')
复制代码

那如题中,是否可以使用正则表达式来替代子串

答:不可以,因为使用子串构建正则时,有可能有特殊字符,就有可能出现问题,如下

// 期待结果: 'AhelloX hello3 '
> 'hello. helloX hello3 '.replace(new RegExp('hello. ', 'g'), 'A')
< "AAA"
复制代码

而在 javascript 中替换子串只能使用一种巧妙的办法:str.split('foo').join('bar')

> 'hello. hello. hello. '.split('hello. ').join('A')
< "AAA"
复制代码

真是一个巧(笨)妙(拙)的办法啊!!!!!大概 TC39 也意识到了一个问题,于是出了一个新的 API,在 ESNext

String.prototype.replaceAll()

'aabbcc'.replaceAll('b', '.'); 
// 'aa..cc'
复制代码

详细文档在 String.prototype.replaceAll

总结(及直接答案)

两种办法

  • str.split('foo').join('bar')
  • str.replaceAll('foo', 'bar'),在 ESNext 中,目前支持性不好


相关文章