I’m using javascript, jQuery and regex to add anchors (#hashtag) around all hashtags on the page. The regex detects things that are hashtags, and then I use jQuery to re-write the HTML and a javascript .replace() to add in the anchor tags. I also do a javascript if statement so it doesn’t replace things inside of script and style tags.
var regExp = /(\W)#([a-zA-Z_]+)(\W)/gm;
var boxLink = "$1<a class='tagLink' onClick=\"doServer('#$2')\">#$2</a>$3"
$('body').children().each(function(){
if (($(this).get(0).tagName.toLowerCase() != 'style')
&& ($(this).get(0).tagName.toLowerCase() != 'script')
) {
$(this).html($(this).html().replace(regExp, boxLink));
}
});
});
Simple enough… right?
The problem is that I’m making a plugin, so developers will deploy this on their websites. The html rewrite ($(this).html($(this).html().replace(regExp, boxLink));) breaks seemingly random areas of javascript on websites. It also messes up some HTML structure sometimes. It’s just a really messy thing to be doing on lots of different sites.
So rather then fix the re-write, I’d like to just find another way to do this. Is there any way I can accomplish the same thing (adding anchor tags around all hashtags on the page) without re-writing the entire HTML on the page each load?
If not, how can I tweak the javascript I have so it isn’t so conflicting with javascript on people’s sites.
This replaces every textnode with a hash tag on this page with:
You can substitute the regex to match yours 🙂
P.S
getTextNodesInfunction was taken from this post :https://stackoverflow.com/a/4399718/776575