-3

Possible Duplicate:
How to replace plain URLs with links?

I am looking to make the user's life a little easier by parsing text input (via javascript) to find all URLs, then link them (wrap tags) so users can just click them. Facebook and even SO does something similar to give you an idea of what I'm looking for.

function censorLinks(text) {
    return text.replace(
        new RegExp('(https?://[^\\s]+)', 'g'),
        '<a href="$1" target="_blank">$1</a>'
    );
}

I don't need to support every protocol. I think http and https is find for now. I'm assuming everything beyond http:// up to the white space is a URL. This almost works but there is one tiny problem: if the URL ends with a period, the period gets included. I suppose it is a valid URL but I think it is unlikely in my situation. How can I prevent the period?

Community
  • 1
  • 1
styfle
  • 22,361
  • 27
  • 86
  • 128

1 Answers1

1

Like @Truth said, this may be a duplicate post but...

I was recently doing something similar, haven't tested this but maybe this'll wrok...

    var email = /(\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,6})/gim;
    var url = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;

    function convert(input) {
        return input
            .replace(url,'<a href="$1" target="blank">$1</a>')
            .replace(email, '<a href="mailto:$1">$1</a>');
    }

Edit: fixed typo

styfle
  • 22,361
  • 27
  • 86
  • 128
Nick Briz
  • 1,917
  • 3
  • 20
  • 34