For a side-project in reactJs i want to do something very particular. Let's imagine you have a text like this in a div:
" Hello world (it's a test) can you help me ? you will be my angel <3"
My user can select the text like you select a text to copy it. But there is a button next to my text. If you select a part of the text and click on it the part of the text will be underline. is it clear ? :)
So now here it's my problem. Actually it works fine but when i select a bigger text (more than 3 lines) or if there is unclose parenthesis in the text my website crash.
Her my code :
function underligne(text, selectedText) {
const termRegex = new RegExp(`(${selectedText})(?=[^>]*<)`, "gi");
return text.replace(termRegex, "<span style='background-color:#3fff3d'>$1</span>");
}
So as i said it works fine but the regex crash if the selectedText is like :
(it's a test
or
(it's a test)
or if the selectedText is longer than around 3 lines
So i tried to remove the regex and make a big loop but it's not nice at all. I tried different type of regex but i always get the same trouble with the unclosed parenthesis.
The only things i want it's to underline every occurence of the selectedText in the text. Whatever the size of the selectedText or the character in it.
Btw sorry for my english i tried to do my best to remove as much as i can the spelling mistake
EDIT :
Just a last question please :)
I want to improve the escapeRegExp to escape <br>
tag how can i do that ?
i tried this
function escapeRegExp(string) {
return string.replace(/<br ?\/?>[.*+?^${}()|[\]\\]/g, '\\$&');
}
or this :
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\](<br ?\/?>)/g, '\\$&');
}
but without success :/