I'd suggest:
var string = "This is a test string.",
needle = "test",
re = new RegExp(needle, "gi"),
newString = string.replace(re, "<strong>" + needle + "</strong>");
console.log(newString);
JS Fiddle demo.
Note that I used <strong></strong> rather than <b></b> (deliberately), though, of course, you can use whatever element-type you like. Also, the gi flags:
g is for a global search, rather than simply stopping at the first match, and
i is for case-insensitive, so 'test' will match Test,tESt and so on...
Edited to preserve capitalization of the matched string/substring:
var string = "This is a Test string.",
needle = "test",
re = new RegExp(needle, "gi"),
newString = string.replace(re, function(a,b){
return "<strong>" + a + "</strong>";
});
document.getElementById('input').appendChild(document.createTextNode(string));
document.getElementById('result').innerHTML = newString;
JS Fiddle demo.
Edited to create a more functional/reusable approach:
function formatMatches(el, needle, wrapper) {
if (!el || !needle) {
return false;
}
else {
var re = new RegExp(needle, "gi"),
haystack = el.textContent,
o = '<' + wrapper + '>',
c = '</' + wrapper + '>';
return haystack.replace(re, function(a) {
return o + a + c;
});
}
}
var needle = "test",
el = document.getElementById('input'),
wrapper = 'strong';
document.getElementById('result').innerHTML = formatMatches(el, needle, wrapper);
JS Fiddle demo.
References: