How to put links in words automatically with javascript?

3

If the page contains the words "contact", "help" and others .. turn them into a link:

<a href='http://meusite.com/pagina1.html'>contato</a>

<a href='http://meusite.com/pagina2.html'>ajuda</a>

Example:

You may need help , if you have any doubts, please go to contact with us

    
asked by anonymous 22.07.2018 / 03:41

2 answers

5

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]);
   }
}
    
22.07.2018 / 07:05
2

Assuming this text is inside an HTML element, for example:

<div class="texto">Você talvez precise de ajuda, caso tenha duvidas entre em contato conosco</div>

You can use this function:

function substitiuirPalavraPorLink (palavras) {
  var textos = document.getElementsByClassName('texto');

  if (textos) {
    for (i = 0; i < textos.length; i++) {
      for (j = 0; j < palavras.length; j++) {
        if (textos[i].innerHTML.search(palavras[j].palavra) ) {
          textos[i].innerHTML=textos[i].innerHTML.replace( palavras[j].palavra, criarLink(palavras[j].link, palavras[j].palavra));
        }
      }
    }
  }

}

function criarLink (link, palavra) {
  return '<a href="' + link + '">' + palavra + '</a>';
}

function Substituir(){
//define quais palavras serão substituidas pelo respctivo link
var palavras = [{
    palavra: 'contato',
    link: 'http://meusite.com/pagina1.html'
  },
  {
    palavra: 'ajuda',
    link: 'http://meusite.com/pagina1.html'
  }
];
substitiuirPalavraPorLink(palavras);
}
<div class="texto">Você talvez precise de ajuda, caso tenha duvidas entre em contato conosco</div>

<div class="texto">Caso tente entrar em contato, não peça ajuda</div>

<input type='button' onCLick="Substituir();" value="Substituir" />

Basically what the routine does is find all tags with the Text class using the method getElementsByClassName and replace the words provided in a list.

    
22.07.2018 / 04:27