Brian Armstrong
Brian Armstrong

Reputation: 19863

escape_javascript and single quotes

I have this in a some_file.js.erb file

console.log("<%= escape_javascript(translate "I can't do that") %>")

Which outputs: I can&#x27;t do that

I can't figure out why it is not rendering the single quote correctly. Any ideas?

Upvotes: 2

Views: 1971

Answers (4)

aldrien.h
aldrien.h

Reputation: 3635

If you plan put some ruby code inside javascript,

then escape_javascript will not work even if you put .html_safe to it.

This works for me,

#{sanitize("content with ` single ` quote".gsub("'", "&rsquo;"))}

=> replace all single quotes with `&rsquo;` (html code)
=> sanitize helper to render it properly in view.

Upvotes: 0

thedevlpr
thedevlpr

Reputation: 1101

I believe the escaped JS won't give you HTML safe code

Try console.log("<%= escape_javascript "I can't do that".html_safe %>")

Upvotes: 0

infused
infused

Reputation: 24337

That's exactly what escape_javascript is supposed to do. From the documentation for escape_javascript:

Escapes carriage returns and single and double quotes for JavaScript segments.

Upvotes: 0

Ege Ersoz
Ege Ersoz

Reputation: 6571

You can use the html_safe method on the string.

console.log("<%= escape_javascript "I can't do that".html_safe %>")

Upvotes: 5

Related Questions