This solution uses replace
with Regular Expression to replace occurrences. However, it is necessary that the text to be analyzed is inside some tag.
Example:
document.addEventListener("DOMContentLoaded", function(){
var links = {
"contato aqui": "linkcontatoaqui.html",
"abaixo-assinado": "linkaabaixoassinado.html",
"ajuda": "linkajuda.html",
"linha": "linklinha.html"
}
var bodi = document.querySelectorAll("body *:not(script)");
for(var x=0; x<bodi.length; x++){
var html = bodi[x].innerHTML;
for(var i in links){
var re = new RegExp("\b(?![^<]*?>)("+i+")(?!>)", "gi");
html = html.replace(re, ' <a href="'+links[i]+'">$1</a>');
}
bodi[x].innerHTML = html;
}
});
Contato ← este não é alterado porque não está dentro de uma tag
<div class="ajuda">
<div data-url="http://ajuda.com">ajuda</div>
<br>
abaixo-assinado galinha ou linha
<br>
Você talvez precise de ajuda, caso tenha duvidas entre em Contato conosco
<p>Você talvez precise de Ajuda caso tenha duvidas entre em contato.</p>
</div>
<p>Você talvez precise de Ajuda caso tenha duvidas entre em contato aqui ajuda.</p>
The expression "\b(?![^<]*?>)("+i+")(?!>)"
will search the elements HTML for each item name of the links
object and make the replace
for the $1
group and applying its value to the <a>
tag.
By the regular expression pattern, only words that are not within the% limiters (attributes, properties, etc.) will be overwritten. The <>
are the options of the expression. The gi
will capture all occurrences, and g
will ignore the case sensitive (see in the example both the word "help" and "help" have been replaced).
This i
selector will select all elements that are in document.querySelectorAll("body *:not(script)");
(except out-of-tag text, as stated at the beginning of this response), and body
will prevent scripting content from being selected, which does not matter in this case.
In the :not(script)
object you can create a list of words, followed by the link you want for each:
var links = {
"contato": "linkcontato.html",
"ajuda": "linkajuda.html" ← link da palavra
} ↑
palavra a ser
substituída
Edit
To skip tags that do not have innerHTML you can include the contents of the first links
in a for
that does this check:
for(var x=0; x<bodi.length; x++){
if(bodi[x].innerHTML.length){ // ← ignora tags sem innerHTML
var html = bodi[x].innerHTML;
for(var i in links){
var re = new RegExp("\b(?![^<]*?>)("+i+")(?!>)", "gi");
html = html.replace(re, ' <a href="'+links[i]+'">$1</a>');
}
bodi[x].innerHTML = html;
}else{
console.log(bodi[x]);
}
}