简体   繁体   中英

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?

您可以在字符串上使用html_safe方法。

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

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.

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM