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'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\'s small ears
Edit
@Stefan's comment under MrYoshiji's answer worked for me.
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 %>"
 }
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With