Javascript 变量中转义引号的通用方法
我有一个表单,用户可以在其中输入任何 HTML。
var title = "Cool <a href="http://google.com">Check This</a>"
正如您所看到的,变量具有 "
,但也可以是 '
。如果存在 "
,则会导致错误。有什么更好的方法来解决这个问题?将转义字符串存储在数据库中,如下所示?
$title = str_replace('"', "'", $_REQUEST['title']); // Replace double quote with single quote as js variable above is wrapped with double quotes.
或者在页面上显示之前将其转义? jQuery 中的任何类似 escape 的东西可以在这里提供帮助吗?
I have a form where users can enter any HTML.
var title = "Cool <a href="http://google.com">Check This</a>"
As you can see, the variable is having "
but it can be also '
. It causes an error if there is "
. What is better way to fix this? Storing escaped string in database like below?
$title = str_replace('"', "'", $_REQUEST['title']); // Replace double quote with single quote as js variable above is wrapped with double quotes.
Or escape it before showing on page? Anything in jQuery like escape that can help here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好吧,你无法使用 JavaScript 来转义它,因为 JavaScript 需要了解你想要转义的内容以及你想要转义的内容。如果您使用 PHP,则可以在插入 JavaScript 之前使用
addslashes()
。无论如何,您应该小心不要允许插入任何 HTML。错误转义的 HTML(例如允许插入
)可能允许执行各种危险的操作,例如窃取所有 cookie。
Well, you cannot escape it using JavaScript because JavaScript needs to see what you want to escape and you want to escape that. If you use PHP, you can use
addslashes()
prior to inserting into JavaScript.Anyways, you should be careful of allowing to insert any HTML. Wrongly escaped HTML (like allowing to insert
<script>
) can allow to do various dangerous stuff, like stealing all cookies.