1
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 replaces in my html and inserted the links as desired.
But now I need to handle some cases and I couldn’t think of a simple way to solve.
Basically the cases I need to deal with are:
- Do not convert the string to link when inside another link.
- Do not convert the string to link when it is the value of a tag attribute.
The html I perform find and replace, I get this way:
<p><a class="btn" href="http://www.google.com/">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/" 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;
}
};
Considering the html received and the function, when executing and passing the link and the word Google, it changes everywhere, however this breaks the html.
Any suggestions on how to fix this?
have as for example the cases you do not want to convert?
– Guilherme Lautert
it is possible to create an array with the positions of everything you want to change, and create another array with the positions of everything that should not be changed, and validate when doing replace
– Filipe Ricardo