Luca Romagnoli
Luca Romagnoli

Reputation: 12455

Extract and add link to URLs in string

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>

Upvotes: 2

Views: 2001

Answers (3)

anon
anon

Reputation: 1

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

Upvotes: 0

koosa
koosa

Reputation: 3040

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.

Upvotes: 1

Mark Wilkins
Mark Wilkins

Reputation: 41222

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>' )

Upvotes: 3

Related Questions