Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace a period with HTML character

I am having a problem with some code. I put in an input and text in a paragraph is highlighted using <mark>. But when I add a period to highlight all the periods, the code freaks out and gives me the actual html code and has random highlights. So I tried to add a replacer to change the periods. Now it won't freak out but with won't 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 removing the "\b" in the regex but that didn't fix it.)

like image 238
Hawkeye Avatar asked Mar 06 '16 01:03

Hawkeye


1 Answers

Replace . to \\. ( escape it, \\ backslash required to keep backslash when you would pass string to RegExp) :

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

Reason of your error is that . is character which has special meaning in RegExp, so you have to escape it prior passing to RefExp.

See Special characters meaning in regular expressions for more information.

Good Luck )!

like image 58
Andriy Ivaneyko Avatar answered Sep 30 '22 04:09

Andriy Ivaneyko