使用正则表达式 (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/