How to store a string in a JavaScript variable that has Single Quotes and Double Quotes?

╄→гoц情女王★ 提交于 2019-12-04 12:52:44

You could save that kind of string by modifying it on the server side before output, like this:

html_content = "<?=addslashes($string);?>"

The method addslashes($string) would then escape any double quotes at runtime before feeding it to the JavaScript variable.

Well you could always use JavaScript's escape function to serialize your string before storing it. That'll work.

I think the bigger issue here, though, is that single quotes are actually not valid the way you're attempting to use them in your id attribute like that (per the HTML spec). It always has to be double quotes. If the code that that's coming from isn't under your control, then there's not much you can do, it's just broken; but if it is under your control, you should fix it too.

Use json_encode to pass almost any variable from PHP to JavaScript.

html_content=<?=json_encode($string)?>;

In the case of a string, it will automatically add quotes and any necessary escaping.

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