I need regex for replace words inside text and not part of the words.
My code that replace 'de' also when it’s part of the word:
str="de degree deep de";
output=str.replace(new RegExp('de','g'),'');
output==" gree ep "
Output that I need: " degree deep "
What should be regex for get proper output?
str.replace(/\bde\b/g, '');
Note that
RegExp('\\bde\\b','g') // regex object constructor (takes a string as input)
and
/\bde\b/g // regex literal notation, does not require \ escaping
are the same thing.
The \b
denotes a "word boundary". A word boundary is defined as a position where a word character follows a non-word character, or vice versa. A word character is defined as [a-zA-Z0-9_]
in JavaScript.
Start-of-string and end-of-string positions can be word boundaries as well, as long as they are followed or preceded by a word character, respectively.
Be aware that the notion of a word character does not work very well outside the realm of the English language.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With