Replace period with HTML symbol

I have a problem with some code. I put the input and the text in the paragraph is highlighted using <mark> . But when I add a period to highlight all periods, the code freaks out and gives me the actual html code and has random glare. So I tried to add a replacement to change the periods. Now he will not worry, but with will not highlight anything. Here is my code to try to replace the period with the html character number ( &#46; ):

 var i = document.getElementById("Bar").value; var inpu = $.trim(i); var inp = inpu.replace(".", "&#46;"); var SearchReq = new RegExp("(\\b" + inp + "\\b)", "gim"); var Notes = document.getElementById("NoteHolder").innerHTML; var after = Notes.replace(SearchReq, "<mark class=" + ColorOptionReady + ">$1</mark>"); document.getElementById("NoteHolder").innerHTML = after; 

What is the problem with the code? (I tried to remove the "\ b" in the regex, but that didn't fix it.)

+5
source share
1 answer

Replace . to \\. (remove it, \\ backslash needed to save the backslash when you pass the string to RegExp):

 var inp = inpu.replace(".", "\\."); 

The reason for your mistake is that . is a symbol that has special meaning in RegExp, so you need to get away from it before going to RefExp.

For more information, see Special Characters in Regular Expressions .

Luck)!

+5
source

Source: https://habr.com/ru/post/1244503/


All Articles