2

I have several strings that have links in them. For instance:

var str = "I really love this site: http://www.stackoverflow.com"

and I need to add a link tag to that so the str will be:

I really love this site: <a href="http://www.stackoverflow.com">http://www.stackoverflow.com</a>
Phrogz
  • 296,393
  • 112
  • 651
  • 745
Luca Romagnoli
  • 12,145
  • 30
  • 95
  • 157
  • 2
    You could use actionpack like described here: http://stackoverflow.com/questions/1442143/ruby-linkify-for-urls-in-strings/1442382#1442382 – Mischa May 13 '11 at 14:34
  • possible duplicate of [Turn URLs and @* into links](http://stackoverflow.com/questions/4571229/turn-urls-and-into-links) – Phrogz May 13 '11 at 15:24

3 Answers3

3

One possibility would be to use the URI class to let it do the parsing. Something along the lines of this:

require 'uri'

str = "I really love this site: http://www.stackoverflow.com"
url = str.slice(URI.regexp(['http']))
puts str.gsub( url, '<a href="' + url + '">' + url + '</a>' )
Mark Wilkins
  • 40,729
  • 5
  • 57
  • 110
1

You can use URI.extract for this:

str = "I really love this site: http://www.stackoverflow.com and also this one: http://www.google.com"

URI.extract(str, ['http', 'https']).each do |uri|
  str = str.gsub( uri, "<a href=\"#{uri}\">#{uri}</a>" )
end

str

The above also matches multiple URLs in one string.

koosa
  • 2,966
  • 3
  • 31
  • 46
0

Here you go, working code :) strips out the http/s prefix in the displayed link also

note you should regex on uri+" " so it catches the links properly... and then you need to add a space at the beginning to catch links at the end that don't have a trailing space...

thisString = yourString+" " # add space to catch link at end
URI.extract(thisString, ['http', 'https']).each do |uri|
  linkURL = uri
  if(uri[0..6] == "http://")
    linkURL = uri[7..-1]
  elsif(uri[0..7] == "https://")
    linkURL = uri[8..-1]
  end
  thisString = thisString.gsub( uri+" ", "<a href=\"#{uri.to_s}\">#{linkURL.to_s}</a> " )
end
anon
  • 1