MrStatic
MrStatic

Reputation: 63

Auto link a phrase on a page using javascript

The code below is meant to put links in words, but it works with only one word, I would like it to work with two words or more

Example:

"contact us": "www.example.com/contact.html",
"need help": "www.example.com/help.html",
"quick-thinking": "www.example.com/quick.html",

The code:

document.addEventListener("DOMContentLoaded", function(){
   var links = {
      "contact": "www.example.com/contact.html",
      "help": "www.example.com/help.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("([\\s|&nbsp;]"+i+"(?:(?=[,<.\\s])))", "gi");
         var matches = html.match(re);
         if(matches){
            matches = html.match(re)[0].trim();
            html = html.replace(re, function(a){
               return ' <a href="'+links[i]+'">'+a.match(/[A-zÀ-ú]+/)[0].trim()+'</a>';
            });
         }
      }
      bodi[x].innerHTML = html;
   }
});
<div>
Please contact us if you need help
</div>

Update:

I'm not sure if this part is working, but I want you to not change words from script, img and class="thisclass" or .thisclass:

document.querySelectorAll("body *:not(script)")

Upvotes: 3

Views: 89

Answers (1)

dev8080
dev8080

Reputation: 4020

You were just replacing it wrong.

a.match(/[A-zÀ-ú]...

needs to allow for a space character

a.match(/[A-zÀ-ú\s]...

See below:

document.addEventListener("DOMContentLoaded", function(){
   var links = {
      "contact us": "www.example.com/contact.html",
      "need help": "www.example.com/help.html",
      "hyphen-spaced-word" : "www.example.com/help.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("([\\s|&nbsp;]"+i+"(?:(?=[,<.\\s])))", "gi");
         var matches = html.match(re);
         //console.log(matches);
         if(matches){
            matches = html.match(re)[0].trim();
            html = html.replace(re, function(a){
               return ' <a href="'+links[i]+'">'+a.match(/[A-zÀ-ú\s-]+/)[0].trim()+'</a>';
            });
         }
      }
      bodi[x].innerHTML = html;
   }
});
<div>
Please contact us if you need help. See hyphen-spaced-word.
</div>

Upvotes: 2

Related Questions