Skip to content

Instantly share code, notes, and snippets.

@broslav
Created September 14, 2018 13:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save broslav/39ffb3f6bdedb0fb2835d972c198b00f to your computer and use it in GitHub Desktop.
Save broslav/39ffb3f6bdedb0fb2835d972c198b00f to your computer and use it in GitHub Desktop.
Function to highlight user input inside autosuggest component
highlightWords = (string, highlight) => {
let counter = 0;
let str = string;
let index = string.toLowerCase().indexOf(highlight.toLowerCase());
let result = [];
while(index > -1) {
result.push(<span key={counter++}>{str.slice(0, index)}</span>);
result.push(<mark key={counter++}>{str.slice(index, index + highlight.length)}</mark>);
str = str.slice(index + highlight.length);
index = str.toLowerCase().indexOf(highlight.toLowerCase());
}
result.push(<span key={counter++}>{str}</span>);
return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment