Skip to content Skip to sidebar Skip to footer

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 sea

Solution 1:

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:

functionupdateHaystack(input, needle) {
    return input.replace(newRegExp('(^|\\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;

Solution 2:

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

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

Worked for me.

Solution 3:

findstring: /(^|\s)(cows)(\s|$)/ignewstring: '$1<b>$2</b>$3'

The \b markers are for "word boundaries"; the /ig flags are for case-ignoring and global matching, respectively.

The usage of the () captures and then $1/$2/$3 in the new string text is so that the capitalization and spacing of whatever was matched will be preserved.

Solution 4:

var needle = 'cows';

var regexp = newRegExp('(^|\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>');

Post a Comment for "Javascript Regex: How To Bold Specific Words With Regex?"