I want to highlight some sentences in a text and I created this function:
function highlightReviewAux(content,text) {
return content.replace(new RegExp(`\b${text}\b`, "gi"), match => {
return '<span class="highlightText">' + match + '</span>';
});
It works except for this content ". […] I booked this for a very special occasion, trusting that (the current title( “5 star The best 1 bed in Shoreditch” "
I think it’s for the special characters.
This is the error:
SyntaxError: Invalid regular expression: /bNice wooden Bedroom floor showed poor care when decorating as white paint splatted all over it. [...] I booked this for a very special occasion, trusting that (the current title( “5 star The best 1 bed in Shoreditch” b/: Unterminated group
Can you help me? I’m here for more than 2 hours and can’t find the solution…
3
Answers
I see the problem
It was when your
text
had a parenthesis. I think the idea of creating a regexp from arbitrary text is causing problems, and may be unnecessary.Just split the content wherever you find the text, and then rejoin
When you rejoin, you can use your chosen replacement string as the joining string.
Your problem is that when some string with special characters used by Regular Expressions like ".", "(" or ")" is passed through the
text
parameter, there is a high chance that creating that Regular Expression will fail. But there is a built-in solution for this:You need to escape some characters inside the string when you generate the regular expression using the constructor, otherwise they will be interpreted and can generate the error you get.
The chars in this case would be:
.^$*+?()[{|
You can escape them by adding a in front of them.