Created
January 27, 2016 23:26
-
-
Save jketcham/34b4906294b32382a92e to your computer and use it in GitHub Desktop.
highlight words in a string that match a given term
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
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