Convert URL to href link with regexp

Discussion in 'JavaScript' started by lbalance, Aug 6, 2009.

  1. #1
    I found the following code online, but it doesn't work exactly like I need it to. It only passes the domain name as "$1" instead of the whole URL.

    result=result.replace(/(http\:\/\/[\w\.\-\?\!\&\=]+)/g,'<a href="$1">[LINK]</a>');
    Code (markup):
    Example:
    http://forums.digitalpoint.com/faq.php?faq=rules

    Converted with the code above would look like:
    <a href="http://forums.digitalpoint.com">[LINK]</a>/faq.php?faq=rules
     
    lbalance, Aug 6, 2009 IP
  2. premiumscripts

    premiumscripts Peon

    Messages:
    1,062
    Likes Received:
    48
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Try this:

    result=result.replace(/(https?:\/\/([-\w\.]+)+(:\d+)?(\/([\w\/_\.]*(\?\S+)?)?)?)/g,'<a href="$1">[LINK]</a>');
    
    Code (markup):
     
    premiumscripts, Aug 6, 2009 IP
    lbalance likes this.
  3. lbalance

    lbalance Peon

    Messages:
    381
    Likes Received:
    18
    Best Answers:
    0
    Trophy Points:
    0
    #3
    beautiful. works like a charm.

    thanks!
     
    lbalance, Aug 7, 2009 IP
  4. lbalance

    lbalance Peon

    Messages:
    381
    Likes Received:
    18
    Best Answers:
    0
    Trophy Points:
    0
    #4
    i just noticed a URL that broke the expression.

    the URL had periods (.) in it and they weren't included on the href.
    can you change the expression to include periods?
     
    lbalance, Aug 8, 2009 IP
  5. premiumscripts

    premiumscripts Peon

    Messages:
    1,062
    Likes Received:
    48
    Best Answers:
    0
    Trophy Points:
    0
    #5
    Hi, sorry it didn't work for you. You can try searching regexlib.com for other URL regexes. (regexlib.com/Search.aspx?k=url&c=-1&m=5&ps=20)
     
    premiumscripts, Aug 9, 2009 IP