Skip to content Skip to sidebar Skip to footer

Javascript Regex: Bolding Needles In A Haystack

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 exp

Solution 1:

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>');
}

Solution 2:

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');
}

Solution 3:

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>"

Solution 4:

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

'(^|\\s)(' + needle + '[@!#.(),?]*)(\\s|$)'

Post a Comment for "Javascript Regex: Bolding Needles In A Haystack"