function highlightPartial(subject, search) {
var special = /([?!.\\|{}\[\]])/g;
var spaces = /^\s+|\s+/g;
var parts = search.split(" ").map(function(s) {
return "\b" + s.replace(spaces, "").replace(special, "\\$1");
});
var re = new RegExp("(" + parts.join("|") + ")", "gi");
subject = subject.replace(re, function(match, text) {
return "<b>" + text + "</b>";
});
return subject;
}
var result = highlightPartial("N University Ave", "n univ av");
// ==> "<b>N</b> <b>Univ</b>ersity <b>Av</b>e"
Side note - this implementation does not pay attention to match order, so:
var result = highlightPartial("N University Ave", "av univ n");
// ==> "<b>N</b> <b>Univ</b>ersity <b>Av</b>e"
If that's a problem, a more elaborate sequential approach would become necessary, something that I have avoided here by using a replace()
callback function.