Escaping characters in JavaScript single and double quotes [duplicate]

僤鯓⒐⒋嵵緔 提交于 2019-11-29 02:30:25

When using single quotes you only need to escape single quotes, not double quotes.

(EDIT: And vice versa!)

document.write('<img src="http://www.google.com" onClick="foo(\'bar\');" />'); 

You only need to escape the same kind of quotes that you are using.

By now, you've got the picture: no need to escape quotes that you're not using as delimiters of that particular string. However: what is best practice is a different story. I know of some people who will tell you that 'always escaping quotes' is a good habit to get into. I disagree. Unlike some other languages JavaScript is reasonably lenient when it comes to escaped characters: in your second example, the backslashes won't be printed out.

This is not always the case, so My suggestion would be: be consistent in which quotes you use (single || double) and escape only the ones that need escaping. Depending on what other languages you're using, you might want to think a bit on which quotes you're going to use. If you're using PHP, for example, stick to single quotes, as double quotes do more than just delimiting a string. If you're used to writing C-like languages (or Java), best stay in the habit of using double quotes, since there is an even bigger difference between single and double quotes in those languages

document.write('<img src="http://www.google.com" />'); Will work just fine.

same counts for document.write("<img src='http://www.google.com' />");

<html>
<body>

<script type="text/javascript">

document.write(escape("<img src=\"http://www.google.com\" />"));

</script>

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