How to Automatically Link URLs in Rails

Let’s say you have a Rails app and you’d like any URLs in any plain text string to be automatically hyperlinked. Well, then you’ll need this:
.gsub(/((http|https)://[a-z0-9]+([-.]{1}[a-z0-9]+)*.[a-z]{2,5}(([0-9]{1,5})?/.*)?)/, '<a href='1'>1</a>')

For example:
I blog at

"I blog at".description.gsub(/((http|https)://[a-z0-9]+([-.]{1}[a-z0-9]+)*.[a-z]{2,5}(([0-9]{1,5})?/.*)?)/, '<a href='1'>1</a>')

Results in:
I blog at

One Reply to “How to Automatically Link URLs in Rails”

Comments are closed.