Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
136
rated 0 times [  140] [ 4]  / answers: 1 / hits: 36024  / 14 Years ago, mon, february 7, 2011, 12:00:00

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?


More From » regex

 Answers
8
str.replace(/bdeb/g, ''); 


Note that



RegExp('\bde\b','g')   // regex object constructor (takes a string as input)


and



/bdeb/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.


[#93860] Saturday, February 5, 2011, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
emilianoc

Total Points: 568
Total Questions: 109
Total Answers: 99

Location: Oman
Member since Sat, Jan 7, 2023
1 Year ago
;