Javascript Regex: How to bold specific words with regex?

javascript, regex

Solution

Here is a regex to do what you're looking for:

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

In JS, replacement is like so:

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

Wrapped up neatly in a reusable function:

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;

Problem

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

Original source