0ktfmw
Last Updated: February 25, 2016
·
5.81K
· citizen428

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

2 Responses
Add your response

15462

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.

over 1 year ago ·
24865

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.

over 1 year ago ·