Javascript: regex for replace words inside text and not part of the words
I need regex for replac开发者_开发百科e 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.
str="de degree deep de";
output=str.replace(/\bde\b/g,'');
You can use the reg ex \bde\b
.
You can find a working sample here.
The regex character \b
act as a word separator. You can find more here.
You should enclose your search characters between \b
:
str="de degree deep de";
output=str.replace(/\bde\b/g,'');
You can use a word boundary as Arun & Tomalak note.
/\bde\b/g
or you can use a space
/de\s/g
http://www.regular-expressions.info/charclass.html
精彩评论