0

I have text:

I love Stackoverflow so much, so please visist http://stackoverflow.com

How can I transform it to:

I love Stackoverflow so much, so please visist <a href='http://stackoverflow.com'>http://stackoverflow.com</a>

in the easiest way in javascript?

Note that the url in text could be without http:// and without wwww, but I want the attribute hrefto contain at least http://. Also take in consideration that some links are https://

einstein
  • 13,389
  • 27
  • 80
  • 110
  • http://regexlib.com/Search.aspx?k=URL&AspxAutoDetectCookieSupport=1 – mplungjan Sep 07 '11 at 09:02
  • 1
    possible duplicate of [jQuery Text to Link Script?](http://stackoverflow.com/questions/247479/jquery-text-to-link-script) – Haim Evgi Sep 07 '11 at 09:02
  • possible duplicate of [How to replace plain URLs with links?](http://stackoverflow.com/questions/37684/how-to-replace-plain-urls-with-links) – mplungjan Sep 07 '11 at 09:28
  • Can somone pls tell me an answer for url strings that doesn't contain `http://` or/and `www` in the url? Given this regex `/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;` from @mplungjan's link? – einstein Sep 07 '11 at 09:46

1 Answers1

3

Try this -

var text = 'I love Stackoverflow so much, so please visist http://stackoverflow.com';
result = text.replace(/(\b(https?|ftp|file):\/\/[\-A-Z0-9+&@#\/%?=~_|!:,.;]*[\-A-Z09+&@#\/%=~_|])/img, '<a href="$1">$1</a>');
alert(result);

Working demo - http://jsfiddle.net/5cKhn/

RegEx taken from RegEx library within RegEx Buddy

ipr101
  • 24,096
  • 8
  • 59
  • 61
  • So taking this already posted answer: [How to replace plain URLs with links?](http://stackoverflow.com/questions/37684/how-to-replace-plain-urls-with-links/37687#37687), adding a slash and an m, and no credits makes this a good answer? – mplungjan Sep 07 '11 at 09:35
  • @mplungjan, I genuinely hadn't seen that answer. I'd only looked at the duplicate reported by Haim Evgi. I took the regex from the regex library in RegEx Buddy - I'll change the answer to credit that. – ipr101 Sep 07 '11 at 09:48
  • @ipr101: Can you create regex for urls that doesn't contain `http://`and `www` too in RegEx Buddy? Like `stackoverflow.com` becomes `stackoverflow.com` and `www.stackoverflow.com` becomes `www.stackoverflow.com` – einstein Sep 07 '11 at 10:00
  • @Woho87 That would be more difficult as you'd have to define what was and wasn't a URL. For instance, `stackoverflow.com` is a sequence of characters then a dot then another sequence of characters, so you might pick-up other non-url matches using that logic. You'd really have to decide the rules you wanted to use to match a URL then take it from there. – ipr101 Sep 07 '11 at 10:29
  • You could look for location.host in the text to at least convert the links that mentioned the current server – mplungjan Sep 07 '11 at 15:49