I created a simple JavaScript function to replace any string with a link within an area in my html. Until then I pass some parameters and this function does a replace in my html and inserted the links as desired.
But now I need to handle some cases and I could not think of a simple way to solve it.
Basically the cases I need to deal with are:
- Do not convert string to link when inside another link.
- Do not convert string to link when value is one tag attribute.
The html that I perform find and replace, I get:
<p><a class="btn" href="http://www.google.com.br/">Mecanismo de Busca</a>, loren ipsun dolor loren Google.</p>
<p>Loren ipsun dolor loren Google, loren ipsun dolor <span>Loren</span>, <b>Google</b>.</p>
<p>Acesse o <a class="btn" href="http://www.google.com.br/" title="Acesse o Google">Google</a></p>
My job is this:
var jsLib = {
replaceToHref: function (word, url, target) {
var wordWithTag = '<a href="' + url + '" title="' + word + '" target="' + target + '">' + word + '</a>'
var content = document.getElementById('page-content-replace');
var result = content.innerHTML.replace(new RegExp("(\s|\.|\-|^|;|\!|\?|\(|\)|\:|\\)(" + word + ")(\s|\.|\-|^|;|\!|\?|\(|\)|\:|\\)", "g"), "$1" + wordWithTag + "$3");
content.innerHTML = result;
}
};
Given the html received and the function, when executing and passing the link and the word Google, it changes everywhere, but this breaks the html.
Any suggestions how to resolve this?