Dan Rubio Dan Rubio - 3 months ago 11
Javascript Question

How can I unescape and remove quot; from data served by rails into javascript

This question has been asked a few times on stackoverflow but I've yet to find a way how to unescape double quotes from a rails instance variable that I am trying to serve up in order for my highcharts to make use in my respective

js.erb
file.

Here is the code that I have:

class FooController < ApplicationController
def foo
@foo_bar = @foo.map { |f| f.version }
end
end


The
@foo_bar
instance variable should return
["1.2.3","3.0","4.5"]
. Instead I keep getting this
[&quot;1.2.3&quot;, &quot;3.0quot;,quot;4.5quot]
; and I can't seem to remove this. I've tried using Rail's
escape_javascript
method but it still doesn't work. I've tried
JSON.parse(instance_variable)
and that didn't work either. Lastly, I tried to
.gsub
the quotes and manually replace them with
\"
and that didn't work either. Why won't the double quotes escape and how can I get this at the root of the problem? I've tried to solve this both server and client side but to no avail. Does anyone have anymore suggestions?

Answer

You're inlining data that's being treated as HTML "unsafe", so you have to declare it as safe in your template.

<%= @foo_bar.to_json.html_safe %>

Note that when you declare something as "safe" that means you're confident you're not exposing yourself to XSS attacks because you're using some other escape method. In your case make sure you're emitting properly escaped JavaScript or JSON.