验证JavaScript函数名称 [英] Validate a JavaScript function name

查看:79
本文介绍了验证JavaScript函数名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是一个正则表达式,我可以用它来匹配一个有效的JavaScript函数名称...



例如, myfunction 是有效的,但是我的< \ fun \> ction 将是无效的。

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


解决方案

@ bobince的帖子在下面,以获得更正确和彻底的答案。这个答案已被保留以供参考,并被编辑为更少错误。

JavaScript中的有效名称必须以Unicode字母开头( \p {L} ),美元符号或下划线可包含任何这些字符以及数字,组合变音符号(重音符号)以及各种连接符标点和零宽度空格。此外,它不能是JavaScript语言保留的一个单词(例如 abstract as boolean break byte case

完整的正则表达式解决方案在普通的JavaScript中会非常复杂,但是 XRegExp Unicode插件可以大大简化任务。 这个在线函数名称测试器可能也很有用。



这是一个不完整的正则表达式,仅使用美国ASCII字母:

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

您还必须检查它是否与任何保留字(例如abstract,boolean,break,字节,...,while,with等)。这里是该列表的开始,以及一个示例函数:

var isValidFunctionName = function(){
var validName = / ^ [$ A-Z _] [0- 9A-Z _ $] * $ / I;
var reserved = {
'abstract':true,
'boolean':true,
// ...
'with':true
};
返回函数(s){
//确保一个有效的名字而不是保留的。
返回validName.test(s)&& !保留[S];
};
}();


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

解决方案

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

这篇关于验证JavaScript函数名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆