Check this:
var my_text = "Camden Barfly, 49 Chalk Farm Road, London, NW1 8AN, london again for testing"
var search_words = "barfly london";
String.prototype.highlight = function(words_str)
{
var words = words_str.split(" ");
var indicies = [];
var last_index = -1;
for(var i=0; i<words.length; i++){
last_index = this.toLowerCase().indexOf(words[i], last_index);
while(last_index != -1){
indicies.push([last_index, words[i].length]);
last_index = this.toLowerCase().indexOf(words[i], last_index+1);
}
}
var hstr = "";
hstr += this.substr(0, indicies[0][0]);
for(var i=0; i<indicies.length; i++){
hstr += "<b>"+this.substr(indicies[i][0], indicies[i][1])+"</b>";
if(i < indicies.length-1) {
hstr += this.substring(indicies[i][0] + indicies[i][1], indicies[i+1][0]);
}
}
hstr += this.substr(indicies[indicies.length-1][0]+indicies[indicies.length-1][1], this.length);
return hstr;
}
alert(my_text.highlight(search_words));
// outputs: Camden <b>Barfly</b>, 49 Chalk Farm Road, <b>London</b>, NW1 8AN, <b>london</b> again for testing