Ruby: make plain text links clickable
If you have some plain text containing links and want to turn them into actual hyperlinks, Ruby's URI
module has a method to generate a regular expression for finding them. Combined with our old friend String#gsub
, this makes the task almost too easy:
text.gsub(URI.regexp, '<a href="\0">\0</a>')
If you are using Rails you may want to use simple_format to also conveniently convert newlines into line breaks and paragraphs:
simple_format(text).gsub(URI.regexp, '<a href="\0">\0</a>').html_safe
Written by Michael Kohl
Related protips
2 Responses
Nice catch. But you know what, it works badly if the string has something like
"Check my new post: DOGS in www.google.com "
When using " {something}: " it recognizes it like a link as well.
Hi,
I have as scenario like text "some thing www.google.com and somethink google.com"
here is it apply linke to both or only the text with www domain. if not can you advice possible solution to achieve this. i am trying in rails.