Converting URLs to clickable hyperlinks using Javascript

Discussion in 'Javascript' started by Jason, Jan 18, 2007.

  1. Jason

    Jason Guest

    I have a piece of text that could have http://somelink.com in it. I
    want to convert every potential hyperlink to an actual link in HTML,
    like <a href='$link'>$link</a>

    What is the best way to do this in Javascript?
     
    Jason, Jan 18, 2007
    #1
    1. Advertising

  2. Jason

    Matt Kruse Guest

    Jason wrote:
    > I have a piece of text that could have http://somelink.com in it. I
    > want to convert every potential hyperlink to an actual link in HTML,
    > like <a href='$link'>$link</a>


    var x = document.getElementById('myDivWithLinkText');
    x.innerHTML = x.innerHTML.replace(/(http:\/\/[^ ]+)/g,'<a
    href="$1">$1</a>/');

    Make sure your text doesn't contain actual links, or it will screw them up.
    If your case is more complicated than the simplest possible case, then you
    would need to expand on this solution.

    --
    Matt Kruse
    http://www.JavascriptToolbox.com
    http://www.AjaxToolbox.com
     
    Matt Kruse, Jan 18, 2007
    #2
    1. Advertising

  3. Jason

    ASM Guest

    Jason a écrit :
    > I have a piece of text that could have http://somelink.com in it. I
    > want to convert every potential hyperlink to an actual link in HTML,
    > like <a href='$link'>$link</a>
    >
    > What is the best way to do this in Javascript?


    Don't know what is the best ... you could try :


    onload = function() {
    var L = document.links;
    // or
    // L = document.getElementsByTagName('A');
    for(var i=0; i<L.length; i++)
    {
    L.href = 'http://somelink.com';
    if(L.text) { L.text = 'my link'; }
    else L.innerHTML = 'my link';
    }
    }


    --
    Stephane Moriaux et son (moins) vieux Mac déjà dépassé
    Stephane Moriaux and his (less) old Mac already out of date
     
    ASM, Jan 18, 2007
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Kaidi
    Replies:
    5
    Views:
    475
    Andrew Thompson
    Jan 4, 2004
  2. Nathan Sokalski

    Converting Relative URLs into Absolute URLs

    Nathan Sokalski, Aug 11, 2008, in forum: ASP .Net
    Replies:
    1
    Views:
    749
    Sriram Srivatsan
    Aug 12, 2008
  3. Adam Monsen

    JDBC URLs ...not really URLs?

    Adam Monsen, Feb 6, 2009, in forum: Java
    Replies:
    11
    Views:
    6,222
    Adam Monsen
    Feb 8, 2009
  4. Simon Strandgaard
    Replies:
    8
    Views:
    124
    Simon Strandgaard
    Aug 23, 2004
  5. Shri Borde
    Replies:
    1
    Views:
    115
    Eric Hodel
    May 19, 2009
Loading...

Share This Page