Don't use HTML string hacking. Imagine what would happen if you tried to replace over <span title="blah click here blah">...</span>
with an <a>
tag... massively broken markup. And that's only the beginning of the problems.
Instead, iterate over the text nodes in the part of the document you want to examine, looking for text matches and inserting a new link using DOM-style methods.
jQuery doesn't really help you much here as it has no functionality for handling text nodes. Instead, use something like the findText()
function from this question and use splitText
to split up the text node:
findText($('#fancy_hover')[0], /\bClick here\b/gi, function(node, match) {
node.splitText(match.index+match[0].length);
var link= document.createElement('a');
link.href= 'http://www.example.com/';
link.appendChild(node.splitText(match.index));
node.parentNode.insertBefore(link, node.nextSibling);
});