Difference between single quotes and double quotes

2019-01-01 02:35发布

问题:

This question already has an answer here:

  • When to use double or single quotes in JavaScript? 40 answers

I know that in PHP, the only difference between double quotes and single quotes is the interpretation of variable inside a string and the treatment of escape characters.

In JavaScript, I often see double quotes used in strings. Is there a particular reason for that, or are single quotes exactly the same as double quotes?

回答1:

You\'ll want to use single quotes where you want double quotes to appear inside the string (e.g. for html attributes) without having to escape them, or vice versa. Other than that, there is no difference.



回答2:

There is a difference in JSON - The JSON standard specifies that all key,value pairs should be in double quotes. (thanks to wulfgarpro in the comments), so I have started switching to using double-quotes as much as possible so that I don\'t make mistakes when dealing with JSON.



回答3:

Absolutly no difference. FREE QUOTING YEEHHAAA



回答4:

Unlike PHP, for which using double or single quotes changes how the string is interpreted, there is no difference in the two syntaxes in ECMAScript. A string using double quotes is exactly the same as a string using single quotes. Note, however, that a string beginning with a double quote must end with a double quote, and a string beginning with a single quote must end with a single quote.

Nicholas C. Zakas - Professional JavaScript for Web Developers



回答5:

They are the same, I usually use single quotes but thats because I am a .net developer and asp.net in particular so it aids me in distinguishing between the 2 types of strings.



回答6:

I just found a difference. I\'m making a mobile website, but I\'ve mostly been testing on desktop Firefox. This works fine on Firefox:

var searchArray = searchValue.split(\' \'); // Split a string at the spaces.

BUT... it doesn\'t work on mobile Safari (iPhone 3GS running iOS 6.1). To make it work on mobile Safari, you have to use double quotes:

var searchArray = searchValue.split(\" \"); // Split a string at the spaces.

If you don\'t use double quotes, it doesn\'t split, it just puts the whole string into the first array element. That was a real puzzler for me and took quite a while to figure out; I dunno what even made me try switching the quotes, because I thought they were always supposed to act the same way. I haven\'t found anything on this problem by googling, so maybe this will help someone.