So for every prediction the google places autocomplete API also returns matched substrings for each one.
Input: San 68
Prediction: San Francisco 68
Matched substrings: [{ offset: 0, length: 3 }, { offset: 15, length: 2 }]
Expectation: San Francisco 68
My goal is to highlight parts of the prediction using the matched substrings. Now there is a few challenges. I could use the replace
function and replace every substring with <b>str</b>
, but it returns a string which means unless I use dangerouslySetInnerHTML
this method doesn't work.
I also don't think there is a way to replace multiple substrings. I tried to use the reduce
function but after the first loop it wouldn't really work because the indexes would be wrong.
const highlight = (text, matched_substrings) => {
return matched_substrings.reduce((acc, cur) => {
return acc.replace(
acc.substring(cur.offset, cur.length),
(str) => `<b>${str}</b>`
)
}, text)
}
So is there a way to do this? I think React makes this more complicated.