What characters are valid for JavaScript variable names?

后端 未结 12 1878
情深已故
情深已故 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条回答
  •  梦毁少年i
    2020-11-21 04:54

    The accepted answer would rule out a lot of valid identifiers, as far as I can see. Here is a regular expression that I put together which should follow the spec (see chapter 7.6 on identifiers). Created it using RegexBuddy and you can find an export of the explanation at http://samples.geekality.net/js-identifiers.

    ^[$_\p{L}][$_\p{L}\p{Mn}\p{Mc}\p{Nd}\p{Pc}\u200C\u200D]*+$
    

    In addition, the name cannot be one of the following reserved words.

    break, do, instanceof, typeof, case, else, new, var, catch, finally, return, void, continue, for, switch, while, debugger, function, this, with, default, if, throw, delete, in, try, class, enum, extends, super, const, export, import, implements, let, private, public, yield, interface, package, protected, static, null, true, false

提交回复
热议问题