How to parse links and escape html entities?

910 views Asked by At

I have some user provided content that I want to render.

Obviously the content should be escaped, rails does this by default. However I also want to parse the text so that urls are presented as links.

There is an auto_link helper which does just that. However no matter what order I do this in I can't get the desired result.

Take content:

content                                             
  => "<img src=\"foo\" />\\r\\n\\r\\nhttp://google.com"

If this is escaped, because the slashes in the url are escaped, auto_link will not work:

Rack::Utils.escape_html(content)                    
  => "&lt;img src=&quot;foo&quot; &#x2F;&gt;\\r\\n\\r\\nhttp:&#x2F;&#x2F;google.com"

If I use auto_link first obviously the link will be escaped. Additionally auto_link strips unwanted content rather than escaping. If a script tag is present in the input I want it escaped not removed.

auto_link(content)                                  
  => "<img src=\"foo\" />\\r\\n\\r\\n<a href=\"http://google.com\">http://google.com</a>"

Any idea how to do get the desired output?

Thanks for any help.

3

There are 3 answers

0
Chris On BEST ANSWER

The solution I ended up using was ditching auto_link, letting Rack escape my content server side and then parsed the links out of the text on the client side using https://github.com/gabrielizaias/urlToLink

$('p').urlToLink();
3
benjaminjosephw On

You could strip out all the escaped whitespace characters with content.gsub!(/\\./, ""). Then you'll be able to use auto_link.

0
haakon On

I've had success with:

auto_link(h(content))