Last active
August 29, 2015 14:13
-
-
Save vermilion1/a598058b3f8740f4d861 to your computer and use it in GitHub Desktop.
Highlight string parts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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