Reputation: 4579
I have a Searchbar on Top, the results get rendered into a fairly basic Listview. I want to have every word that's typed into the searchbar (not case sensitive) highlighted in the search result (string).
At the moment I do a basic split:
let split = question.title.split(this.state.searchInput);
and rendering it to:
<Text style={styles.title}>
{split[0]}
</Text>
{split.length > 1 ?
<View style={{flexDirection: 'row'}}>
<Text style={styles.fatTextResult}>
{this.state.searchInput}
</Text>
<Text style={styles.title}>
{split[1]}
</Text>
</View>
:
null
}
This split obviously doesn't work when typing in 2 words that aren't connected in the search result. How can I accomplish that?
atm it looks like this..
Upvotes: 1
Views: 776
Reputation: 10588
Try this:
highlightWord( word , search ){
var newWord = word.replace(/[.,\/#!$%\^&\*;:{}=\-_`~()]/g,"");
if ( search.toLowerCase().indexOf(newWord.toLowerCase()) != -1 ){ // if word in question
// highlight it
return <Text style={{fontWeight:'bold'}}>{word}</Text>
}
else{
return <Text>{word}</Text>
}
}
renderRow( question ){
let split = question.title.split(' '); //divide question in words
textViews = [];
for (var i=0 ; i<split.length ; i++){
var word = split[i]; // get words
textViews.push( highlightWord(word,this.state.searchInput) );
}
// return all words together (highlighted or not)
return <View style={{flexDirection:'row'}}>{ textViews }</View>
}
EDIT
I added the first line on highlightWord
to handle words with punctuation characters.
Upvotes: 1