Friday, February 23, 2024
 Popular · Latest · Hot · Upcoming
rated 0 times [  81] [ 4]  / answers: 1 / hits: 18892  / 15 Years ago, tue, august 4, 2009, 12:00:00

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, milk some COWS

would turn into

<b>cows</b> at, 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? 


More From » regex


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


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;

[#98986] Monday, August 3, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.

Total Points: 118
Total Questions: 81
Total Answers: 102

Location: Kazakhstan
Member since Thu, Dec 23, 2021
2 Years ago