Skip to content

Instantly share code, notes, and snippets.

@jketcham
Created January 27, 2016 23:26
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 jketcham/34b4906294b32382a92e to your computer and use it in GitHub Desktop.
Save jketcham/34b4906294b32382a92e to your computer and use it in GitHub Desktop.
highlight words in a string that match a given term
function matchSearchTerm(string, matchTerm) {
if (!matchTerm) return string;
var words = string.split(' ');
var final = '';
var parsedWords = [];
words.forEach((word, index) => {
if (word.toLowerCase().indexOf(matchTerm) > -1) {
if (final) parsedWords.push(final);
final = '';
parsedWords.push(<span className="found_word" key={index}>{word} </span>);
return;
}
final += word + ' ';
});
parsedWords.push(final);
return parsedWords;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment