1

Let's say that I have a string

string_with_url = 'Random text https://myurl.com'

Is it possible to wrap the url with an anchor tag and only make the wrapped text html safe?

Currently I have to do the following

def add_anchor(message)
    url_regex = %r{(?:https?)://\S+}i
    string_with_url.gsub url_regex, '<a href="\0" target="_blank">\0</a>'

render add_anchor(string_with_url).html_safe

Even though I am only adding the anchor tag here, I am forced to make the wrong string html safe.

Siva
  • 1,256
  • 3
  • 13
  • 29
  • 1
    That'll break down on things like `https://example.com/">` – tadman Oct 18 '16 at 18:08
  • 1
    Looks like you want something like the [`autolink` gem](https://github.com/tenderlove/rails_autolink). – tadman Oct 18 '16 at 18:09
  • I think you may be under the impression that `html_safe` makes the string html safe ... it does not ... it is a mechanism to flag that a string is html safe and prevents it from being html escaped. – David Oct 18 '16 at 18:17
  • Does auto_link not do the same thing here? – Siva Oct 18 '16 at 18:23

0 Answers0