I'm currently writing a function in Javascript which tags specific words.
I have a Box called <code> ... </code> in which i will be writing JS code. I am to lazy to set all tags for syntax highlighting by myself, so i want to have a function to do that for me.
Example: <obj>this</obj>.functionName(); <- obj tag will hightlight "this" in a specific color.
But if "this"
wasn't tagged and occurs like that:
<tab></tab> this.functionName()
;
I want to tag it, but not the already tagged "this"
.
Here is my JS code:
function hightLight(text, tag, html) {
var taggedText = ("<" + tag + ">" + text + "</" + tag + ">");
var oldHTML = "";
do {
oldHTML = html;
html = html.replace(text, taggedText);
} while(html.localeCompare(oldHTML) != 0);//stop if nothing changed
return html;
}
Use this regex:
/this(?!<\/tab>)/
It uses a negative lookahead so it only matches this
when it is not followed by </tab>
. You could use it like this:
var regex = new RegExp(text + "(?!</" + tag + ">)");
and
html = html.replace(regex, taggedText);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.