JavaScript 的 isalpha 替代品?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6800536/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
isalpha replacement for JavaScript?
提问by forkexec
I've been trying to validate the contents of a form with JavaScript. I need to check if the 'Name' field contains only characters and whitespaces. If any other character is present, I want to display an alert. This was easy to do in C and Java but I just cant seem to find a good replacement in JavaScript. I've read about regular expressions but isn't there an easier alternative, kind of like an in-built function?
我一直在尝试使用 JavaScript 验证表单的内容。我需要检查“名称”字段是否仅包含字符和空格。如果存在任何其他字符,我想显示警报。这在 C 和 Java 中很容易做到,但我似乎无法在 JavaScript 中找到好的替代品。我读过正则表达式,但没有更简单的替代方法,有点像内置函数?
回答by Digital Plane
Using a regex is certainly easier:
使用正则表达式肯定更容易:
//Check for non-alphabetic characters and space
if(name.search(/[^A-Za-z\s]/) != -1)
alert("Invalid name");
Using a for loop:
使用 for 循环:
//charCodeAt() gets the char code in a string
//Upper and lower bounds for upper case characters
var upperBoundUpper = "A".charCodeAt(0);
var lowerBoundUpper = "Z".charCodeAt(0);
//Upper and lower bounds for lower case characters
var upperBoundLower = "a".charCodeAt(0);
var lowerBoundLower = "z".charCodeAt(0);
for (var i = 0; i < name.length; i++) {
var char = name.charCodeAt(i);
if (char <= upperBoundUpper && char >= lowerBoundUpper)
continue;
else if (char <= upperBoundLower && char >= lowerBoundLower)
continue;
//Check for space
else if (name[i] == " ")
continue;
else{ //Not recognized character - not valid
alert("Invalid name");
break;
}
}
jsPerf test for relative speed: http://jsperf.com/checking-is-alphabetic
In my tests, the for loop runs faster.
jsPerf 相对速度测试:http://jsperf.com/checking-is-alphabetic
在我的测试中,for 循环运行得更快。
回答by Delan Azabani
No, not that I know of.
不,不是我所知道的。
Although you can emulate the most basic of isalpha
's functionality with
虽然您可以模拟最基本isalpha
的功能
/^[ a-z]+$/i.test(string)
Unlike isalpha
, this is not locale-aware, works only for the simple Latin alphabet and would be equivalent to forcing isalpha
to run in the C
locale.
与 不同isalpha
,这不是语言环境感知的,仅适用于简单的拉丁字母表,相当于强制isalpha
在C
语言环境中运行。