I need a little help with Regular Expressions.
I'm using Javascript and JQuery to hyperlink terms within an HTML document, to do this I'm using the following code. I'm doing this for a number of terms in a massive document.
var searchterm = "Water";
jQuery('#content p').each(function() {
var content = jQuery(this),
txt = content.html(),
found = content.find(searchterm).length,
regex = new RegExp('(' + searchterm + ')(?![^(<a.*?>).]*?</a>)','gi');
if (found != -1) {
//hyperlink the search term
txt = txt.replace(regex, '<a href="/somelink">$1</a>');
content.html(txt);
}
});
There are however a number of instances I do not want to match and due to time constraints and brain melt, I'm reaching out for some assistance.
EDIT: I've updated the codepen below based on the excellent example provided by @ggorlen, thank you!
Example https://codepen.io/julian-young/pen/KKwyZMr
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…