1

I want to convert the URL string into an HTML link element (<a href="#"></a>) (like Facebook make with his URLs in the text by example)

I tried this solution Convert links from a string to clickable links using Ruby/Rails but I just get some HTML link in plain text...

Example :

I have this

string = "blabla http//www.google.com blabla
lorem ipsum lorem ipsum"

And I would this, not in plain text but as HTML element

<p>blabla</p> 
<a href="http//www.google.com">http//www.google.com</a> 
<p>blabla</p>
<p>lorem ipsum lorem ipsum</p>

Thank you for your help :)

troy
  • 2,145
  • 2
  • 23
  • 31
LinkOfCode
  • 45
  • 6
  • 1
    You might want to have a look at the [`simple_format`](https://apidock.com/rails/ActionView/Helpers/TextHelper/simple_format) view helper method and the [`rails_autolinks`](https://github.com/tenderlove/rails_autolink) gem that was once part of Rails itself. – spickermann Jan 14 '21 at 11:51
  • Maybe this will help you: `URI.extract(string)` https://apidock.com/ruby/v2_5_5/URI/extract/class – Luskmo Jan 14 '21 at 12:51

2 Answers2

0

the plain text can be converted to html by called html_safe method on string. Like '<a href="http//www.google.com">http//www.google.com</a>'.html_safe

CR7
  • 1,056
  • 1
  • 8
  • 18
  • Thank you I don't know why it's not working from controller but it's working from view. But I have another question how prevent javascript code like How just passing http url as html_safe ? – LinkOfCode Jan 14 '21 at 16:02
0

I would split the input into "words", compare each word with a regex for a url, and if it matches, wrap it in a link element.

In this answer I'll just use a simple regex. We'll consider anything starting with http:// or https:// to be a URL. You can use something more advanced if you like.

string = "blabla https://www.google.com blabla lorem ipsum lorem ipsum"

string = string.split.map do |word|
  if /https?:\/\/.*/.match word
    next "<a href=\"#{word}\">#{word}</a>"
  else
   next word
  end
end.join(' ')

puts string #=> blabla <a href="https://www.google.com">https://www.google.com</a> blabla lorem ipsum lorem ipsum

Note that this doesn't actually work with the original string in your answer, because it's not a valid url (it's missing the colon).

iCodeSometime
  • 1,444
  • 15
  • 30