Skip to content

Instantly share code, notes, and snippets.

@mgeraci
Created August 8, 2012 23:14
Show Gist options
  • Select an option

  • Save mgeraci/3299637 to your computer and use it in GitHub Desktop.

Select an option

Save mgeraci/3299637 to your computer and use it in GitHub Desktop.
better coffeescript url detection
# regex is from http://www.regexguru.com/2008/11/detecting-urls-in-a-block-of-text/
exp = ///
\b(?:(?:https?|ftp|file)://|www\.|ftp\.)
(?:\([-A-Z0-9+&@\#/%=~_|$?!:,.]*\)|[-A-Z0-9+&@\#/%=~_|$?!:,.])*
(?:\([-A-Z0-9+&@\#/%=~_|$?!:,.]*\)|[A-Z0-9+&@\#/%=~_|$])
///ig
for url in $(this).text().match exp
# add a protocol if it just starts with www
url_with_protocol = "http://#{url}" if url.match(/^www.+/)
visual_url = url.split('').join('​').replace(/(^.{300}).+/, '$1...')
$(this).html $(this).html().replace(url, "<a href='#{url_with_protocol}'>#{visual_url}</a>")
$(this).addClass('autolinked')
@seanlinsley
Copy link

I have to say, this method reads much better:

formatLinks = ()->
  msg = $("#weeee")
  for text in msg.text().match urlPattern
    url = if text.match(/^(http|https|ftp)/) then text else "http://#{text}"
    msg.html msg.text().replace(text, "<a href='#{url}'>#{text}</a>")

@mgeraci
Copy link
Author

mgeraci commented Nov 13, 2012

ABSOLUTELY. @daxter, that's a much better loop. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment