Example String:
'There is a red car parked in front of a blue house with a fence painted red.'
The strings that are to be highlighted with spans are:
['red car', 'blue house', 'red'].
Expected string:
There is a <span class='redHighlight'>red car</span> parked in front of a <span class='blueHighlight'>blue house</span> with a fence painted <span class='redHighlight'>red</span>.
However when I do a replace by iterating over the array, I end up with nested span tags.
> "There is a <span class='<span class='redHighlight'>red</span>Highlight'><span class='redHighlight'>red</span> car</span> parked in front of a <span class='blueHighlight'>blue house</span> with a fence painted <span class='redHighlight'>red</span>.
Code:
let strToHighlight = 'There is a red car parked in front of a blue house with a fence painted red.';
let stringsToMatch = [{'strVal': 'red car',
'cssClass': 'redHighlight'},
{'strVal': 'blue house',
'cssClass': 'blueHighlight'},
{'strVal': 'red',
'cssClass':'redHighlight'}
];
stringsToMatch.forEach(el => {
let regEx = new RegExp(el.strVal,'g') // replace all occurances
strToHighlight = strToHighlight.replace(regEx, `<span class='${el.cssClass}'>${el.strVal}</span>}`);
console.log(strToHighlight);
})
Any suggestions on how to avoid re-tagging strings either via RegEx or any other method?
EDIT: Each string has to be highlighted with different style classes. Editing the strToMatch array to array of objects holding the name of the CSS class to apply.