Skip to content

Instantly share code, notes, and snippets.

@cgiacomi
Created May 9, 2015 10:45
Show Gist options
  • Save cgiacomi/926cf6a02ec16d08423c to your computer and use it in GitHub Desktop.
Save cgiacomi/926cf6a02ec16d08423c to your computer and use it in GitHub Desktop.
Find Matching String in Javascript and adorning it with span and class
/*
* Taken from https://github.com/ghiden/angucomplete-alt/blob/master/angucomplete-alt.js
*/
function findMatchString(target, str) {
var result, matches, re;
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
// Escape user input to be treated as a literal string within a regular expression
re = new RegExp(str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'i');
if (!target) { return; }
matches = target.match(re);
if (matches) {
result = target.replace(re,
'<span class="'+ scope.matchClass +'">'+ matches[0] +'</span>');
}
else {
result = target;
}
return $sce.trustAsHtml(result);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment