Escape String - Output rails string in Javascript

17,581

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 %>"
 }
Share:
17,581

Related videos on Youtube

cclerv
Author by

cclerv

Updated on December 13, 2020

Comments

  • cclerv
    cclerv over 3 years

    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.

  • cclerv
    cclerv over 10 years
    The output is now Tom\&#x27;s small ears
  • MrYoshiji
    MrYoshiji over 10 years
    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.
  • cclerv
    cclerv over 10 years
    It works when I output it directly, but I want to put the value in a javascript variable
  • MrYoshiji
    MrYoshiji over 10 years
    I think the Javascript understands that this &#x27; is actually a '. Try to alert or console.log this value to see if Javascript replaces this ASCII code into the corresponding caracter '.
  • Stefan
    Stefan over 10 years
    Rails seems to escape ', try <%== instead of <%=
  • Mike
    Mike almost 7 years
    Please do not do this unless you have already verified that @product.name is a sanitized string that will not cause an HTML injection.
  • davmac
    davmac almost 7 years
    @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).
  • Zhenya
    Zhenya almost 7 years
    @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)
  • MrYoshiji
    MrYoshiji almost 7 years
    @Ievgen see the first answer's second comment here: stackoverflow.com/questions/7996695/… quoting: "The double equal means that the string is not escaped, as in raw"