views:

73

answers:

4

Related (but not the same):

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 and I want special characters (such as @!#.()) to be ignored in the search

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?

I've got this currently:

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

unfortunately it doesn't bold words that are concatenated with a special char... eg. !cow does not turn into !<b>cow</b>

Thank you

+1  A: 

It sounds like \b should do what you want. It's a zero-width match of "word boundaries".

function updateHaystack(input, needle) {
    return input.replace(new RegExp('\\b(' + needle + ')\\b','ig'), '<b>$1</b>');
}
Laurence Gonsalves
Why `new RegExp()` instead of literal regex syntax?
Tomalak
The snippet is based on the snippet in the question. I only made changes necessary to make it work.
Laurence Gonsalves
A: 

So you need to put an optional section for the special char in the regex:

'(^|\\s)(' + needle + '[@!#.(),?]*)(\\s|$)'
Douglas Leeder
+1  A: 

If you want to allow punctuation to be part of the needle, just add it:

function updateHaystack(input, needle) {
    return input.replace(new RegExp('(^|\\s)(' + needle + '[!.,?]?)(\\s|$)','ig'), '$1<b>$2</b>$3');
}
Amber
+1  A: 

Allow any non-whitespace character to be part of the needle:

"cows, at www.cows.com, milk COWS!".replace(/(\s|^)(cow\S*)(\s|$)/ig, '$1<b>$2</b>$3');
// Will return: "<b>cows,</b> at www.cows.com, milk <b>COWS!</b>"
CMS
I believe the `^` in `(^|\b)` is redundant - the start of the string is a word boundary.
Tomalak
Completely agree, edited...
CMS
Hmmm... I was thinking `/\b(cow\S*)\b/ig` to account for strings like `'(cows)'`.
Tomalak
Nah, thinking about it this would break at the closing paren. Your's is better.
Tomalak