23

I'm trying to assign a string value to a javascript object in my .erb file like so:

var data = {
    'name': '<%= @product.name %>',
    ...
};

The problem is, if the value of name is Tom's small ears,

the output of data.name would be Tom&#x27;s small ears.

Is there a way to escape special characters?

I tried doing 'name': '<%= raw @product.name %>' but Uncaught SyntaxError: Unexpected identifier gets output into the console.

Doing <%= escape_javascript @product.name %> outputs Tom\&#x27;s small ears

Edit @Stefan's comment under MrYoshiji's answer worked for me.

Cœur
  • 37,241
  • 25
  • 195
  • 267
cclerv
  • 2,921
  • 8
  • 35
  • 43

2 Answers2

39

You can use escape_javascript() to accomplish that:

var data = {
    'name': "<%== escape_javascript @product.name %>",
    #...
};

Link: http://api.rubyonrails.org/classes/ActionView/Helpers/JavaScriptHelper.html#method-i-escape_javascript

The alias of this method is j:

 var data = {
     'name': "<%== j @product.name %>"
 }
MrYoshiji
  • 54,334
  • 13
  • 124
  • 117
  • The output is now `Tom\'s small ears` – cclerv Sep 17 '13 at 16:16
  • It does display `Tom\'s small ears` for me in my views when I test this code. Try to directly print `<%= j @product.name %>` in a view (not in a javascript tag) and see if the output is the one desired. – MrYoshiji Sep 17 '13 at 16:21
  • It works when I output it directly, but I want to put the value in a javascript variable – cclerv Sep 17 '13 at 16:25
  • I think the Javascript understands that this `'` is actually a '. Try to alert or console.log this value to see if Javascript replaces this ASCII code into the corresponding caracter '. – MrYoshiji Sep 17 '13 at 16:29
  • 6
    Rails seems to escape `'`, try `<%==` instead of `<%=` – Stefan Sep 17 '13 at 16:42
  • @MrYoshiji, can you please explain to me (or point to documentation) what's the difference beween <%== and <%= ? Google is not good at looking for special symbols (or I'm not good at googling them) – Zhenya Aug 02 '17 at 19:29
  • 1
    @Ievgen see the first answer's second comment here: https://stackoverflow.com/questions/7996695/what-is-the-difference-between-and-in-erb-in-rails quoting: *"The double equal means that the string is not escaped, as in raw"* – MrYoshiji Aug 02 '17 at 19:34
-1
var data = {
   'name': '<%=j @product.name.html_safe %>',
   ...
};
Hooopo
  • 1,380
  • 10
  • 16
  • 1
    Please do not do this unless you have already verified that `@product.name` is a sanitized string that will not cause an HTML injection. – Andrew Jun 26 '17 at 21:27
  • @Andrew I believe the `j` (short for `escape_javascript`) will correctly escape the string regardless, right? (meaning that the example here is fine, except that the call to `html_safe` should be unnecessary). – davmac Jul 21 '17 at 14:41