Search code examples
javascriptregexvalidationfunction

Validate a JavaScript function name


What would be a regular expression which I can use to match a valid JavaScript function name...

E.g. myfunction would be valid but my<\fun\>ction would be invalid.

[a-zA-Z0-9_])?

Solution

  • [EDIT] See @bobince's post below for a more correct and thorough answer. This answer has been retained for reference and edited to be less wrong.

    A valid name in JavaScript must start with a Unicode letter (\p{L}), dollar sign, or underscore then can contain any of those characters as well as numbers, combining diacritical (accent) characters, and various joiner punctuation and zero-width spaces. Additionally, it cannot be a word reserved by the JavaScript language (e.g. abstract, as, boolean, break, byte, case, etc).

    A full regular expression solution would be quite complicated in plain JavaScript but the XRegExp Unicode plugin could greatly simplify the task. This online function name tester might also be useful.

    [ORIGINAL] Here is an incomplete regular expression, using only the US ASCII letters:

    var fnNameRegex = /^[$A-Z_][0-9A-Z_$]*$/i;
    

    You also must check that it doesn't match any reserved words (e.g. abstract, boolean, break, byte, ..., while, with, etc). Here's a start for that list, and an example function:

    var isValidFunctionName = function() {
      var validName = /^[$A-Z_][0-9A-Z_$]*$/i;
      var reserved = {
        'abstract':true,
        'boolean':true,
        // ...
        'with':true
      };
      return function(s) {
        // Ensure a valid name and not reserved.
        return validName.test(s) && !reserved[s];
      };
    }();