Hyperlinking URLs (and emails?) in text

Ugly:

class String
def hyperlink
gsub(/(http://|https://|mailto:)([[:alnum:]/!#$%&’()+,.:;=?@~-]+)([[:alnum:]/!#$%&’()+:;=?@~-])/, ‘\1\2\3’)
end
end

… but it generally works, from my few tests.

Anyone got a better version, or care to improve on this one?

Just trying to hyperlink URLs in text (and in future, email addresses, without needing mailto:).

This is a little bit more readable, while still being somewhat compact.
It also gets plain email addresses:

class String
def hyperlink
# define url parts:
chars = Regexp.escape “/!#$\%&'()*+,.:;=?@~-"
url = “https?:\/\/[#{chars}[:alnum:]]+”
email = "(?:mailto:)?[^\s@]+@[[:alnum:].
-]+\.[[:alnum:]._-]+”
# do the substitution:
gsub(/#{url}|#{email}/) do |link|
if link =~ /[1]+:/
%Q(#{link})
else
%Q(#{link})
end
end
end
end

Note that this will not get all email addresses, and it will let a
some urls spill through. But it should get most stuff. Getting it exact
would require more lines of code than I want to look at tonight :slight_smile:

···

On Feb 15, 2004, at 1:27 AM, Ruby Baby wrote:

Ugly:

class String
def hyperlink
gsub(/(http://|https://|mailto:)([[:alnum:]/!#$%&'()+,.:;=?
@~-]+)([[:alnum:]/!#$%&'()
+:;=?@~-])/, ‘\1\2\3’)
end
end

… but it generally works, from my few tests.

Anyone got a better version, or care to improve on this one?

Just trying to hyperlink URLs in text (and in future, email addresses,
without needing mailto:).


  1. a-zA-Z ↩︎

In Message-Id: 20040215092727.GA2685@mail.hitmedia.com
Ruby Baby ruby@hitmedia.com writes:

Just trying to hyperlink URLs in text (and in future, email
addresses, without needing mailto:).

Do you like the following? uri.rb is bundled with current stable releases.

require "uri"

URI.extract("foo bar http://foo.bar.com/foobar mailto:foo@bar.com")
#=> ["http://foo.bar.com/foobar", "mailto:foo@bar.com"]
···


kjana@dm4lab.to February 15, 2004
Out of sight, out of mind.

Hi,

In mail “hyperlinking URLs (and emails?) in text”

Anyone got a better version, or care to improve on this one?

Just trying to hyperlink URLs in text (and in future, email addresses, without needing mailto:).

If you have ruby 1.8.1:

require ‘uri’

text.gsub(URI.regexp(%w(http https ftp))) {|urlstr|
%Q[#{urlstr}]
}

Also, you will want to escape ‘<’ ‘>’ ‘&’ in text:

require ‘uri’
require ‘cgi’

text.gsub(/[<&>“']|#{URI.regexp(%w(http https ftp))}/) {|matched|
case matched
when /[<&>”']/
CGI.escapeHTML(matched)
else
url = CGI.escapeHTML(matched)
%Q[#{url}]
end
}

Regards,
Minero Aoki

···

Ruby Baby ruby@hitmedia.com wrote: