Javascript regex: how daring concrete words with regular expression?

Given the needle and the haystack ... I want to put bold tags around the needle. So, what expression expression would I use with replacement ()? I want the space to be a divisor, and I want the search to be case insensitive.

so say that the needle is "cow" and haystacks

cows at www.cows.com, milk some COWS 

will turn into

 <b>cows</b> at www.cows.com, milk some <b>COWS</b> 

also the keywords must have spaces in it, therefore, if the keyword is "who is mgmt" ...

 great band. who is mgmt btw? 

will turn into

 great band. <b>who is mgmt</b> btw? 

thanks

+7
javascript regex
source share
4 answers

Here is a regex to do what you are looking for:

 (^|\s)(cows)(\s|$) 

In JS, the replacement looks like this:

 myString.replace(/(^|\s)(cows)(\s|$)/ig, '$1<b>$2</b>$3'); 

Wrapped neatly in reusable functions:

 function updateHaystack(input, needle) { return input.replace(new RegExp('(^|\\s)(' + needle + ')(\\s|$)','ig'), '$1<b>$2</b>$3'); } var markup = document.getElementById('somediv').innerHTML; var output = updateHaystack(markup, 'cows'); document.getElementById('somediv').innerHTML = output; 
+12
source share

For those who do not want SPACE as a separator, just do not use \s .

 function updateHaystack(input, needle) { return input.replace(new RegExp('(^|)(' + needle + ')(|$)','ig'), '$1<b>$2</b>$3'); } 

Worked for me.

+9
source share
 findstring: /(^|\s)(cows)(\s|$)/ig newstring: '$1<b>$2</b>$3' 

The \ b markers are for word boundaries; / ig flags are for ignoring and global matching.

Using () captures and then $ 1 / $ 2 / $ 3 in the new text, so that the capital letters and spacing of all matches will be preserved.

+1
source share
 var needle = 'cows'; var regexp = new RegExp('(^|\s)('+needle+')(\s|$)', 'ig'); var old_string = 'cows at www.cows.com, milk some COWs'; var new_string = old_string.replace(regexp, '<b>$1$2$3</b>'); 
-one
source share

All Articles