1

How can I transform all text links in a page into actual links?

For example, I want to change all text links like this:

<p>http://www.google.com</p>

or in a table like this:

<td>http://www.google.com</td>

into this:

<a href="http://www.google.com">http://www.google.com</a>

and this:

<td><a href="http://www.google.com">http://www.google.com</a></td>
Jess
  • 23,901
  • 21
  • 124
  • 145
Chin
  • 19,717
  • 37
  • 107
  • 164
  • Why do you have pages with addresses that are not hyperlinks? – Lee Taylor Apr 01 '13 at 01:37
  • @LeeTaylor, you have never seen this before? For example what about a blog page where someone pastes in a hyperlink and you want to automatically link it. I think this is a really good question and does not deserve a down vote. – Jess Apr 01 '13 at 02:00
  • 1
    @Jessemon Yes, of course. I was asking to try to elicit some more information on how much control the OP has on the content within his pages. – Lee Taylor Apr 01 '13 at 02:05
  • @LeeTaylor. Okay cool. I think it is a good idea to make the hyperlinks on the server-side if possible. :D – Jess Apr 01 '13 at 02:08
  • @Jessemon - Exactly, that's what I was trying to allude to... – Lee Taylor Apr 01 '13 at 02:10
  • Does this answer your question? [How to replace plain URLs with links?](https://stackoverflow.com/questions/37684/how-to-replace-plain-urls-with-links) – Jess Jun 10 '22 at 14:26

1 Answers1

1

This is what you need:

<html>
<head>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
  <script>
    function createLinks(){
      $('p, td').filter(function() {
        return this.innerHTML.match(/(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?/);
      }).each(function(){
        var link = $('<a>', { href: this.innerHTML,
                              text: this.innerHTML });

        if(this.tagName == "P")
          this.parentNode.replaceChild(link[0], this);
        else{
          this.removeChild(this.childNodes[0])
          this.appendChild(link[0]);
        }
      });
    }

    $(document).ready(function(){
      $('#create_links').click(function(){
        createLinks();
      });
    });
  </script>
  <style>
    a{
      display:block;
    }
  </style>
</head>
<body>
  <p>This shouldn't became a link</p>
  <p>http://www.thisshouldbecamealink.com</p>
  <p>http://www.anotherlink.com</p>
  <table>
    <tr>
      <td>Not a link</td>
    </tr>
    <tr>
      <td>http://www.validlink.com</td>
    </tr>
  </table>
  <button id="create_links">Create links</button>
</body>
</html>
Alcides Queiroz
  • 9,456
  • 3
  • 28
  • 43