I have a SearchBar in my application which offers suggestions starting with the input from that SearchBar.
For example: Typing skrillex in the SearchBar will result in the following suggestions:
skrillex
skrillex kyoto
skrillex cinema
skrillex bangarang
skrillex live
I am trying to bold the words in the suggestions which match the input from the SearchBar.
For the same example above, the result would be:
<b>skrillex</b>
<b>skrillex</b> kyoto
<b>skrillex</b> cinema
<b>skrillex</b> bangarang
<b>skrillex</b> live
The code I am currently using is the following:
item.startsWith(this.state.searchText.trim()) ?
[<Text style={{ fontWeight: "bold" }}>{this.state.searchText.replace(/\s\s+/g, ' ')}</Text>,
<Text>{item.slice((this.state.searchText.replace(/\s\s+/g, ' ').length)).replace(/\s\s+/g, ' ')}</Text>]
: (<Text>{item}</Text>)
This works for most cases, but there are some edge cases in which the code above incorrectly outputs a suggestion. For example, typing skrillex.(with a space after the dot) outputs the following suggestions:
skrillex. cinema
skrillex.bangarang
skrillex. live
skrillex. songs
skrillex.com
After running my code from above to bold out the matching words, this is what the output is:
<b>skrillex.</b> cinema
<b>skrillex.</b>angarang
<b>skrillex.</b> live
<b>skrillex.</b> songs
<b>skrillex.</b>om
Basically, the .slice has cut the b from bangarang (skrillex.bangarang) and c from com (skrillex.com).
Can anyone spot where the error is? I am also open to any alternative ways for doing this since I believe mine is not that efficient.