JavaScript中替换所有出现的子字符串的方法

没有简单的方法可以替换JavaScript中所有出现的字符串。Java从一开始就对JavaScript产生了启发,但replaceAll()自1995年以来就开始在字符串上使用该方法!

在本文中,您将学习如何通过拆分和连接字符串以及string.replace()与全局正则表达式结合来替换JavaScript中所有出现的字符串。

此外,您将了解新的提案string.replaceAll()(在第4阶段),该提案将replace all方法引入JavaScript字符串。这是最方便的方法。

1.拆分和合并数组

如果您用Google搜索如何“替换JavaScript中所有出现的字符串”,最有可能找到的第一种方法是使用中间数组。

运作方式如下:

  1. 通过字符串将分割string成:piecessearch
const pieces = string.split(search);
  1. 然后加入将replace字符串放在中间的片段:
const resultingString = pieces.join(replace);

例如,让我们换掉所有空格' '用连字符'-''duck duck go'字符串:

const search = ' ';
const replaceWith = '-';

const result = 'duck duck go'.split(search).join(replaceWith);

result; // => 'duck-duck-go'

'duck duck go'.split(' ')将字符串拆分为:['duck', 'duck', 'go']

然后,['duck', 'duck', 'go'].join('-')通过在片段'-'之间插入来连接片段 ,从而产生字符串'duck-duck-go'

这是一个使用拆分和合并方法的通用辅助函数:

function replaceAll(string, search, replace) {
  return string.split(search).join(replace);
}

replaceAll('abba', 'a', 'i');          // => 'ibbi'
replaceAll('go go go!', 'go', 'move'); // => 'move move move!'
replaceAll('oops', 'z', 'y');          // => 'oops'

这种方法需要将字符串转换为数组,然后再转换为字符串。让我们继续寻找更好的选择。

2.全局正则表达式replace() 

该字符串的方法string.replace(regExpSearch, replaceWith)搜索和替换正则表达式的发生regExpSearchreplaceWith字符串。

要使该方法replace()替换所有出现的模式,您必须在正则表达式上启用全局标志:

  1. g在正则表达式文字的末尾附加:/search/g
  2. 或在使用正则表达式构造函数时,添加'g'到第二个参数:new RegExp('search', 'g')

让我们来替换出现的所有' ''-'

const searchRegExp = /\s/g;
const replaceWith = '-';

const result = 'duck duck go'.replace(searchRegExp, replaceWith);

result; // => 'duck-duck-go'

正则表达式文字/\s/g(请注意g全局标志)与space匹配' '

'duck duck go'.replace(/\s/g, '-')取代了所有比赛/\s/g'-'其结果,'duck-duck-go'

您可以通过在正则表达式中添加标志来轻松进行不区分大小写的替换i

const searchRegExp = /duck/gi;
const replaceWith = 'goose';

const result = 'DUCK Duck go'.replace(searchRegExp, replaceWith);

result; // => 'goose goose go'

正则表达式/duck/gi执行不区分大小写的全局搜索(注释ig标志)。/duck/gi比赛'DUCK',以及'Duck'

调用'DUCK Duck go'.replace(/duck/gi, 'goose')将所有/duck/gi子字符串匹配项替换为'goose'

2.1字符串中的正则表达式

从字符串创建正则表达式时,您必须转义字符,- [ ] / { } ( ) * + ? . \ ^ $ |因为它们在正则表达式中具有特殊含义。

因此,当您要替换所有操作时,特殊字符是一个问题。这是一个例子:

const search = '+';

const searchRegExp = new RegExp(search, 'g'); // Throws SyntaxError
const replaceWith = '-';

const result = '5+2+1'.replace(searchRegExp, replaceWith);

上面的代码段尝试将搜索字符串'+'转换为正则表达式。但是'+'是无效的正则表达式,因此SyntaxError: Invalid regular expression: /+/被抛出。

转义字符'\\+'可以解决问题。

但是,是否值得使用诸如escapeRegExp()之类的函数用作正则表达式来转义搜索字符串?很有可能不会。

2.2字符串替换()

如果第一个参数searchstring.replace(search, replaceWith)是一个字符串,则该方法将替换仅第一次出现search

const search = ' ';
const replace = '-';

const result = 'duck duck go'.replace(search, replace);

result; // => 'duck-duck go'

'duck duck go'.replace(' ', '-') 仅替换空间的第一个外观。

3. replaceAll()方法

最后,该方法string.replaceAll(search, replaceWith)将所有出现的searchstring替换为replaceWith

让我们来替换出现的所有' ''-'

const search = ' ';
const replaceWith = '-';

const result = 'duck duck go'.replaceAll(search, replaceWith);

result; // => 'duck-duck-go'

'duck duck go'.replaceAll(' ', '-')将所有出现的' 'string替换为'-'

string.replaceAll(search, replaceWith) 是替换字符串中所有出现的字符串的最佳方法

请注意,当前,浏览器中对方法的支持是有限的,并且您可能需要polyfill

3.1 replaceAll()replace()之间的区别

字符串方法replaceAll(search, replaceWith)replace(search, replaceWith)工作方式相同,期望两件事:

  1. 如果search参数是一个字符串,replaceAll()替换所有出现searchreplaceWith,而replace() 只有第一次出现
  2. 如果search参数是非全局正则表达式,则replaceAll()抛出TypeError异常。

4.重点介绍

替换所有匹配项的原始方法是通过搜索字符串将字符串分成多个块,将字符串重新连接在一起,将替换字符串放置在块之间:string.split(search).join(replaceWith)。这种方法有效,但是很麻烦。

另一种方法是string.replace(/SEARCH/g, replaceWith)与启用了全局标志的正则表达式一起使用。

不幸的是,由于必须转义正则表达式的特殊字符,因此在运行时无法轻松地从字符串生成正则表达式。而且,处理正则表达式以简单替换字符串的方法令人不知所措。

最后,新的字符串方法string.replaceAll(search, replaceWith)将替换所有出现的字符串。该方法是第4阶段的建议,希望它很快就会应用到新的JavaScript标准中。

我的建议是使用string.replaceAll()替换字符串。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值