有没有办法改变js中的子字符串?

Is there way to change a substring in js?

我有一个像这样的字符串:

def definition():

我想更改单词 def(例如)、单词 def 的每个实例,但不更改属于其他单词的“def” 像这样

console.log("def definition():".specialReplace("def", "abc"));

结果应该是

abc definition():

没有

abc abcinition():

使用String#replace or String#replaceAll with a regular expression:

const specialReplace = (str) => str.replaceAll(/\bdef\b/g, 'abc')
console.log(specialReplace("def definition")) // abc definition
console.log(specialReplace("def definition def")) // abc definition abc

在正则表达式中,\b是匹配任何单词边界的boundary type assertion,例如在字母和space之间。

请注意,相同的序列 \b 也用于字符 class 正则表达式位置 ([\b]) 中,以匹配后面的 space 字符。