Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
167
rated 0 times [  173] [ 6]  / answers: 1 / hits: 31814  / 15 Years ago, tue, january 5, 2010, 12:00:00

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_])?

More From » regex

 Answers
104

[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];
};
}();

[#97917] Friday, January 1, 2010, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
chase

Total Points: 78
Total Questions: 106
Total Answers: 93

Location: Comoros
Member since Tue, Mar 14, 2023
1 Year ago
chase questions
Thu, Mar 31, 22, 00:00, 2 Years ago
Thu, Jul 1, 21, 00:00, 3 Years ago
Sat, Dec 12, 20, 00:00, 4 Years ago
Mon, Sep 14, 20, 00:00, 4 Years ago
;