Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: regex for replace words inside text and not part of the words

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?

like image 730
Ben Avatar asked Feb 07 '11 13:02

Ben


1 Answers

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.

like image 156
Tomalak Avatar answered Oct 14 '22 18:10

Tomalak