I’ve got this bit of jQuery with some javascript and RegEx mixed in:
$(function() {
var regExp = new RegExp("\\b(" + "hashtag" + ")\\b", "gm");
var boxLink = "<a class='taglink' onClick='tagBox()'>$1</a>"
var html = $('body').html();
$('body').html(html.replace(regExp, boxLink));
});
function tagBox() {
alert("It works!")
};
Basically it applies $1 to everywhere that the word “hashtag” appears. Tagbox just brings up an alert that says it works. Simple enough. The change I’d like to make is one so that it won’t jet select the word “hashtag”, but all words with “#” symbols before them.
How can I accomplish this and work it into the script above?
Thanks in advance!
First of all,
$('body').html(html)is a really bad idea. You’ll recreate the DOM, and any event listeners previously bound to nodes within the old structure will no longer function. Traversing the DOM node by node is a better idea. Something like this should do the trick:This code is untested, and no doubt has some bugs, but hopefully I’ve convinced you that this problem is more difficult than it may have appeared at first.