Last active
November 17, 2016 15:39
-
-
Save juannorris/fa32fb015acd1496c6dfd55b5359a1f9 to your computer and use it in GitHub Desktop.
Highlight filter with accent support (ui-select).
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
/** | |
* Highlights text that matches given query for ui-select directive. | |
* | |
* It matches accents and uppercase/lowercase (with support from `normalize` function). | |
*/ | |
function customHighlight() { | |
function escapeRegexp(queryToEscape) { | |
return ('' + queryToEscape).replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1'); | |
} | |
return function (matchItem, query) { | |
if (!matchItem || !query) { | |
return matchItem; | |
} | |
// Get the normalized and escaped version of the search query | |
query = escapeRegexp(normalize(query)); | |
var startIndex, | |
endIndex, | |
toBeReplaced, | |
highlightedItem = ''; | |
// Find and replace all occurrences of query inside matchItem, while preserving case and accents | |
while (matchItem.length) { | |
startIndex = normalize(matchItem).indexOf(query); | |
if (startIndex !== -1) { | |
endIndex = startIndex + query.length; | |
toBeReplaced = matchItem.substring(startIndex, endIndex); | |
highlightedItem += matchItem.substring(0, startIndex) + | |
'<span class="ui-select-highlight">' + toBeReplaced + '</span>'; | |
matchItem = matchItem.substring(endIndex, matchItem.length); | |
} else { | |
// Add the rest of the string | |
highlightedItem += matchItem; | |
matchItem = ''; | |
} | |
} | |
return highlightedItem; | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Based on ui-select's highlight filter.
The filter depends on a
normalize
function (probably not the best name), that takes a string and returns its lowercase non-accented version, see: http://stackoverflow.com/questions/990904/javascript-remove-accents-diacritics-in-stringsI guess the filter should be able to support any other special characters, by updating the normalize function accordingly.
In my case, I just needed Spanish and Portuguese accents support, so here is how
normalize
code looks like: