0

Does ruby have some function to escape escaped quotes? like

name = "some \"thing\""
"<meta property=\"og:title\" content=\"#{name}\" />"

as

"<meta property=\"og:title\" content=\"some \\\"thing\\\"\" />"

Simple way is just do

name.gsub("\"", "\\\"")

but looks weird

Stefan
  • 109,145
  • 14
  • 143
  • 218
Dmitry
  • 3
  • 2

1 Answers1

0

To properly encode a double quote in an HTML attribute value, there are several ways:

  • You can use an unescaped " if the attribute value itself is delimited by '...' or vice-versa: (just like strings in Ruby)
    <meta property="og:name" content='some "thing"' />
    
  • If the attribute value is delimited by "...", you can use the double quote's numeric character reference &#34;:
    <meta property="og:name" content='some &#34;thing&#34;' />
    
  • or its character entity reference &quot;:
    <meta property="og:name" content="some &quot;thing&quot;" />
    

From within Ruby, you could call CGI.escapeHTML: (I'm using Ruby's %(...) percent string literal here for the meta tag string, so I don't have to escape all the ")

require 'cgi'

name = 'some "thing"'
meta = %(<meta property="og:name" content="#{CGI.escapeHTML(name)}" />)
#=> "<meta property=\"og:name\" content=\"some &quot;thing&quot;\" />"

puts meta

Or the tag helper if you're using Rails:

<%= tag(:meta, property: 'og:name', content: name) %>

Both of the above output:

<meta property="og:name" content="some &quot;thing&quot;" />
Stefan
  • 109,145
  • 14
  • 143
  • 218
  • thank you, not think about html encoded symbols way. but I prefer solution from another thread `'string'.dump` – Dmitry Feb 04 '20 at 08:49
  • @Dmitry note that `\"` isn't the proper way to escape double quotes in HTML attributes. – Stefan Feb 04 '20 at 08:52
  • checked with google validator " and \" are the same. But I checked place with json-ld, althrought posted in question example with html tag. Thank you for wide answer. Will use " – Dmitry Feb 04 '20 at 09:33
  • @Dmitry try https://validator.w3.org/ – it will complain about `\"` and accept `"`. – Stefan Feb 04 '20 at 09:44