Skip to content

Instantly share code, notes, and snippets.

@vermilion1
Last active August 29, 2015 14:13
Show Gist options
  • Save vermilion1/a598058b3f8740f4d861 to your computer and use it in GitHub Desktop.
Save vermilion1/a598058b3f8740f4d861 to your computer and use it in GitHub Desktop.
Highlight string parts
/**
* Highlight passed array's strings in the passed string.
* @param {string} string - Original string.
* @param {Array<string>} matched - List of items to highlight.
* @returns {string} Highlighted string.
*/
highlightStr: function (string, matched) {
string || (string = '');
matched || (matched = []);
if (_.isEmpty(matched)) {
return string;
}
var normalizedMatch = _.sortBy(matched, 'length').reverse();
var regexpStr = '(' + normalizedMatch.join('|') + ')';
var regexp = new RegExp(regexpStr, 'gi');
var result = string.replace(regexp, '<b>$1</b>');
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment