javascript – Quotation mark guidelines

Question: Question:

  • html tag attribute value
  • CSS properties (url, etc.)
  • JavaScript string literals

The quotation marks used in these can be either single quotes or double quotes, but I want to unify the style for maintainability.

  • When writing JavaScript directly in the event attribute (onlick etc.) of the html tag
  • When editing an html tag with an attribute value in JavaScript

I want to unify the writing style even when quotation marks are nested like.

Please let me know if there are standard rules and reasonable guidelines for proper use.

Answer: Answer:

I've looked at some style guides I know, but there seems to be no reason for this. Yes, but the conclusion is, " It doesn't matter which one, but bias it to either one ." There are four small factors in considering the difference between single and double quotes.

  • If you have a lot of English text, double quotes are better to avoid escaping single quotes.
  • String values ​​in JSON data must be enclosed in double quotes, so it's better to enclose them in single quotes.
  • Single quote input requires only one key press (non-Japanese key layout)
  • I want to match the quotes output in HTML with the project guidelines.

Which one you lean to is more important than which one is better.

Below are some quotes from some Javascipt style guides.

With Mozilla :

Double-quoted strings (eg "foo") are preferred to single-quoted strings (eg'foo') in JavaScript, except to avoid escaping of embedded double quotes or when assigning inline event handlers.

"Basically double quotes. Switch and use so that there are few escapes."

With Google :

Prefer'over "

For consistency single-quotes (') are preferred to double-quotes ("). This is helpful when creating strings that include HTML:

var msg = 'This is some HTML';

"For unity, we give priority to single quotes. It's convenient if the string contains HTML." Well, the sample code also contains HTML. (Because HTML attributes have double quotes priority )

With jQuery :

jQuery uses double quotes.

var double = "I am wrapped in double quotes"; Strings that require inner quoting must use double outside and single inside.

var html = "<div id='my-id'></div>";

"JQuery uses double quotes. If you want to enclose it in a string, use single quotes", for no reason.

Scroll to Top