如何替换JavaScript中所有出现的字符串

使用正则表达式 (Using a regular expression)

This simple regex will do the task:

这个简单的正则表达式将完成以下任务:

String. replace ( /<TERM>/g , '' )

This performs a case sensitive substitution.

这将执行区分大小写的替换。

Here is an example, where I substitute all occurrences of the word ‘dog’ in the string phrase:

这是一个示例,其中我将所有出现的单词“ dog”替换为字符串phrase

const phrase = 'I love my dog! Dogs are great'
const stripped = phrase . replace ( /dog/g , '' )

stripped //"I love my ! Dogs are great"

To perform a case insensitive replacement, use the i option in the regex:

要执行不区分大小写的替换,请在正则表达式中使用i选项:

String. replace ( /<TERM>/gi , '' )

Example:

例:

const phrase = 'I love my dog! Dogs are great'
const stripped = phrase . replace ( /dog/gi , '' )

stripped //"I love my ! s are great"

Remember that if the string contains some special characters, it won’t play well with regular expressions, so the suggestion is to escape the string using this function (taken from MDN):

请记住,如果字符串包含一些特殊字符,那么它将不能在正则表达式中很好地发挥作用,因此建议使用此函数对字符串进行转义(取自MDN ):

const escapeRegExp = ( string ) => {
  return string . replace ( /[.*+?^${}()|[\]\\]/g , '\\$&' )
}

使用拆分和联接 (Using split and join)

An alternative solution, albeit slower than the regex, is using two JavaScript functions.

尽管比正则表达式要慢,但另一种解决方案是使用两个JavaScript函数。

The first is split(), which truncates a string when it finds a pattern (case sensitive), and returns an array with the tokens:

第一个是split() ,它在找到模式(区分大小写)时会截断字符串,并返回带有标记的数组:

const phrase = 'I love my dog! Dogs are great'
const tokens = phrase . split ( 'dog' )

tokens //["I love my ", "! Dogs are great"]

Then you join the tokens in a new string, this time without any separator:

然后,将令牌连接到新字符串中,这次没有任何分隔符:

const stripped = tokens . join ( '' ) //"I love my ! Dogs are great"

Wrapping up:

结语:

const phrase = 'I love my dog! Dogs are great'
const stripped = phrase . split ( 'dog' ). join ( '' )

翻译自: https://flaviocopes.com/how-to-replace-all-occurrences-string-javascript/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值