问题描述
什么是一个正则表达式,我可以用它来匹配一个有效的JavaScript函数名称...
例如, myfunction
是有效的,但是我的< \ fun \> ction
将是无效的。
[a-zA-Z0-9_])?
,以获得更正确和彻底的答案。这个答案已被保留以供参考,并被编辑为更少错误。
JavaScript中的有效名称必须以Unicode字母开头( 完整的正则表达式解决方案在普通的JavaScript中会非常复杂,但是可以大大简化任务。 可能也很有用。 这是一个不完整的正则表达式,仅使用美国ASCII字母: 您还必须检查它是否与任何保留字(例如abstract,boolean,break,字节,...,while,with等)。这里是,以及一个示例函数: What would be a regular expression which I can use to match a valid JavaScript function name... E.g. [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 ( 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: 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: 这篇关于验证JavaScript函数名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! \p {L}
),美元符号或下划线可包含任何这些字符以及数字,组合变音符号(重音符号)以及各种连接符标点和零宽度空格。此外,它不能是JavaScript语言保留的一个单词(例如 abstract
, as
, boolean
, break
, byte
, case $ c
var fnNameRegex = / ^ [$ A-Z _] [0-9A-Z _ $] * $ / i;
var isValidFunctionName = function(){
var validName = / ^ [$ A-Z _] [0- 9A-Z _ $] * $ / I;
var reserved = {
'abstract':true,
'boolean':true,
// ...
'with':true
};
返回函数(s){
//确保一个有效的名字而不是保留的。
返回validName.test(s)&& !保留[S];
};
}();
myfunction
would be valid but my<\fun\>ction
would be invalid.[a-zA-Z0-9_])?
\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).var fnNameRegex = /^[$A-Z_][0-9A-Z_$]*$/i;
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];
};
}();