Escape String - Output rails string in Javascript
17,581
You can use escape_javascript()
to accomplish that:
var data = {
'name': "<%== escape_javascript @product.name %>",
#...
};
The alias of this method is j
:
var data = {
'name': "<%== j @product.name %>"
}
Related videos on Youtube
Author by
cclerv
Updated on December 13, 2020Comments
-
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
isTom's small ears
,the output of
data.name
would beTom's small ears
.Is there a way to escape special characters?
I tried doing
'name': '<%= raw @product.name %>'
butUncaught SyntaxError: Unexpected identifier
gets output into the console.Doing
<%= escape_javascript @product.name %>
outputsTom\'s small ears
Edit @Stefan's comment under
MrYoshiji's
answer worked for me. -
cclerv over 10 yearsThe output is now
Tom\'s small ears
-
MrYoshiji over 10 yearsIt 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 over 10 yearsIt works when I output it directly, but I want to put the value in a javascript variable
-
MrYoshiji over 10 yearsI 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 '. -
Stefan over 10 yearsRails seems to escape
'
, try<%==
instead of<%=
-
Mike almost 7 yearsPlease do not do this unless you have already verified that
@product.name
is a sanitized string that will not cause an HTML injection. -
davmac almost 7 years@Andrew I believe the
j
(short forescape_javascript
) will correctly escape the string regardless, right? (meaning that the example here is fine, except that the call tohtml_safe
should be unnecessary). -
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 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"