Escaping quotes from Rails Variables when using them for Javascript?

拈花ヽ惹草 提交于 2019-12-04 01:01:11
bobince

when you try alert('I\'m testing'); there's a problem

Backslash is also an escape in Ruby strings! So the string literal:

"alert('I\'m testing');"

means the string:

alert('I'm testing');

the backslash is gone already before JavaScript gets a look at it. When you are writing a JavaScript string literal inside a Ruby string literal you need to escape the escape, \\, to get a real \ that will then, in JavaScript, escape the apostrophe.

escape_javascript correctly generates the backslash for JavaScript, if a backslash was included in its input. But again, if you're writing a string literal, you have to escape the backslash to get a real backslash:

escape_javascript("\b")     -> this is a backspace character!
escape_javascript("\\b")    -> this is backslash-then-letter-b;
                               escaped for JavaScript literal to double-backslash-then-b.

So, this is fine:

"'"+escape_javascript(myvar)+"'"

alternatively, you can use a JSON encoder to create the JavaScript string literal including the surrounding quotes.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!