I'm writing a (dynamic) RegEx parser for plain HTML to extract values. To show the current RegEx result, I want to show the HTML code highlighted with the current result.
I have the HTML code in a variable and my RegEx match function returns the current result and the index of the result.
Therefore, I injected a <span class="highlight">
to the position of the found string, and close it by </span>
after the length of the match.
My current problem is: If I set the element with element.text(newtext), my injected HTML is not parsed.
On the other hand, if I set the element with element.html(newtext), the full HTML is parsed and possibly broken.
If I first escape the HTML tags to not be parsed, the index of RegEx.match of the raw html is not equal to the escaped html, therefore the injection is on the wrong place.
Is there a nice way to handle html code as plain text, but injection of highlighting html goes to the right place using an index?
Example
Think of a full html source code - this is a one line snippet of my weather station:
<td bgcolor="#EDEFEF"><input name="inHumi" disabled="disabled" type="text" value="63" /></td>
The user enters a RegEx matching value="
, therefore value="
should be highlighted in the html string.
Sample code
The JS code looks like this. Think of all set variables are user-defined in an HTML form, therefore the user enters the RegEx and the HTML source code as text, and the RegEx match should be visible in that form.
var rawhtml = '<td bgcolor="#EDEFEF"><input name="inHumi" disabled="disabled" type="text" value="63" /></td>';
var regex = 'value=\"';
var result = rawhtml.match(regex);
var result_string = result[0];
var result_index = result.index;
$("#visiblehtml").html(rawhtml.substring(0, result_index) + "<span class='highlight'>" + rawhtml.substring(index, index + result_string.length) + "</span>" + rawhtml.substring(index + result_string.length));
Inserting this span in the middle of the input field, the html will break. Also, setting the element with .html will parse and show the full rawhtml, not the rawhtml source.