What characters are valid for JavaScript variable names?

后端 未结 12 1916
情深已故
情深已故 2020-11-21 04:26

Which characters can be used for naming a JavaScript variable?

I want to create a small \"extension library\" for my non-JavaScript users here at work (who all seem

12条回答
  •  逝去的感伤
    2020-11-21 04:54

    Before JavaScript 1.5: ^[a-zA-Z_$][0-9a-zA-Z_$]*$

    In English: It must start with a dollar sign, underscore or one of letters in the 26-character alphabet, upper or lower case. Subsequent characters (if any) can be one of any of those or a decimal digit.

    JavaScript 1.5 and later * : ^[\p{L}\p{Nl}$_][\p{L}\p{Nl}$\p{Mn}\p{Mc}\p{Nd}\p{Pc}]*$

    This is more difficult to express in English, but it is conceptually similar to the older syntax with the addition that the letters and digits can be from any language. After the first character, there are also allowed additional underscore-like characters (collectively called “connectors”) and additional character combining marks (“modifiers”). (Other currency symbols are not included in this extended set.)

    JavaScript 1.5 and later also allows Unicode escape sequences, provided that the result is a character that would be allowed in the above regular expression.

    Identifiers also must not be a current reserved word or one that is considered for future use.

    There is no practical limit to the length of an identifier. (Browsers vary, but you’ll safely have 1000 characters and probably several more orders of magnitude than that.)

    Links to the character categories:

    • Letters: Lu, Ll, Lt, Lm, Lo, Nl
      (combined in the regex above as “L”)
    • Combining marks (“modifiers”): Mn, Mc
    • Digits: Nd
    • Connectors: Pc

    *n.b. This Perl regex is intended to describe the syntax only — it won’t work in JavaScript, which doesn’t (yet) include support for Unicode Properties. (There are some third-party packages that claim to add such support.)

提交回复
热议问题