Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Regex: How to bold specific words with regex?

Given a needle and a haystack... I want to put bold tags around the needle. So what regex expression would I use with replace()? I want SPACE to be the delimeter and I want the search to be case insensitive

so say the needle is "cow" and the haystack is

cows at www.cows.com, milk some COWS

would turn into

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

also keywords should be able to have spaces in it so if the keyword is "who is mgmt"...

great band. who is mgmt btw? 

would turn into

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

Thanks

like image 731
rawrrrrrrrr Avatar asked Aug 04 '09 23:08

rawrrrrrrrr


People also ask

What is \b in regex JavaScript?

The RegExp \B Metacharacter in JavaScript is used to find a match which is not present at the beginning or end of a word. If a match is found it returns the word else it returns NULL. Syntax: /\B/ or new RegExp("\\B") Syntax with modifiers: /\B/g.

What is Slash's regex?

The backslash in combination with a literal character can create a regex token with a special meaning. E.g. \d is a shorthand that matches a single digit from 0 to 9. Escaping a single metacharacter with a backslash works in all regular expression flavors.

What does $1 do in regex?

For example, the replacement pattern $1 indicates that the matched substring is to be replaced by the first captured group.

Does string match regex?

Java - String matches() Methodmatches(regex) yields exactly the same result as the expression Pattern.


1 Answers

For those who don't want SPACE as the delimiter, simply don't use \s.

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

Worked for me.

like image 200
Mohd Sulaiman Avatar answered Sep 17 '22 15:09

Mohd Sulaiman