user502052
user502052

Reputation: 15259

Making a link from a string

I am using Ruby on Rails 3 and I would like to extract from a string the first URL or e-mail address and then use the resulting string (examples: "http://www.test.com", "mailto:[email protected]", ...) as the href attribute value used in a HTML <a href="resulting_string_value">Test link name</a>.

How can I do that in the safest way?

P.S.: I know the RoR auto_link method, but that does not accomplish what I need.

Upvotes: 1

Views: 396

Answers (3)

bpaulon
bpaulon

Reputation: 356

Ok, you probably didn't want a regular expression, but it works, and you might use it as a helper

The code for urls:

str = "http://someurl.com/"
str.scan(/http:\/\/([^\/]*)/)

The code for emails:

str = "mailto:[email protected]"
str.scan(/mailto:([^ ]*)/)

Putting it all together:

result_array = str.scan(/mailto:([^ ]*)|http:\/\/([^\/]*)/)
if result_array.length > 0
  result = result[0][0] unless empty? result[0][0] 
  result = result[0][1] unless empty? result[0][1] 
end

Upvotes: 0

DigitalRoss
DigitalRoss

Reputation: 146053

Domain and host names can have - or . characters in them and email usernames have a system-specific definition. Here is a hURL matcher that tries to share the DNS parse.

/((https*\:\/\/)|(mailto:[^@]+@))(\/*[\w\-rb.]+)*/

Upvotes: 1

Summit Guy
Summit Guy

Reputation: 305

If you just want the first link in the string, you can just use match. Also, you want to use a non-greedy match:

str.match(/mailto:([^ ]*?( |$|\n))|http:\/\/([^\/]*?)( |$|\n)/) 

You can add more checking for valid email addresses, etc. if you'd like.

Once you've got the string, you can use auto_link to make a link from it.

Upvotes: 0

Related Questions