I have a string like:
def definition():
I want to change every instance of "def" but not the "def" in word definition.
like this
console.log("def definition():".specialReplace("def", "abc"));
and result should be
abc definition():
not
abc abcinition():
CodePudding user response:
Use 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
In the regular expression, \b
is a boundary type assertion that matches any word boundary, such as between a letter and a space.
Note that the same sequence \b
is also used inside character class regular expression positions ([\b]
), to match the backspace character.