简体   繁体   English

在javascript中检查字符是否是多个字母的最佳方法?

[英]Best way to check if a character is a number of letter in javascript?

In javascript whats the best way to check if a character (length 1), is a number (ie 0, 1, 2, 3, 4, 5, 6, 7, 8, 9) or a letter (ie A to Z, a to z)?在javascript中,检查字符(长度为1)是数字(即0、1、2、3、4、5、6、7、8、9)还是字母(即A到Z, a 到 z)?

Thanks谢谢

I wrote a little test case for you, at least for the numeric checking function.我为你写了一个小测试用例,至少是数字检查功能。

Considering the fact that all functions returns true with either a numberic 1 or a string '1' literal, using an Array seems to be the fastest way (at least in Chrome).考虑到所有函数都使用数字1或字符串'1'文字返回 true,使用Array似乎是最快的方法(至少在 Chrome 中)。

var isNumericChar = (function () {
    var arr = Array.apply(null, Array(10)).map(function () { return true; });
    return function (char) { return !!arr[char]; };
})();

However, if you accept that it might return false for 1 , the switch statement is then significantly faster.但是,如果您接受它可能会为1返回 false,那么 switch 语句会明显更快。

Why not:为什么不:

function isNumber(i) {
    return (i >= '0' && i <= '9');
}

function isLetter(i) {
    return ((i >= 'a' && i <= 'z') || (i >= 'A' && i <= 'Z'));
}

Try this.尝试这个。

function validate_string() {

var str = "a"; //change to desired value;
var regX = new RegExp("([0-9A-Za-z])");
var ans = false;

if(str.length == 1) {
    ans = regX.test(str);    
}

return ans;

}

Edit: Refactored my answer.编辑:重构我的答案。

function validateString(char) {
    let regx = new RegExp(/^[0-9A-Za-z]{1}$/g);
    return regx.test(char);    
}

validateString('4'); // true
validateString('as'); // false
validateString(''); // false
validateString(); // false

Maybe try something like this也许尝试这样的事情

 var sum = 0; //some value
 let num = parseInt(val); //or just Number.parseInt
 if(!isNaN(num)) {
     sum += num;
 }

This blogpost sheds some more light on this check if a string is numeric in Javascript |这篇博文更详细地说明了 JavaScript 中字符串是否为数字的检查 | Typescript & ES6 打字稿和 ES6

You can check for the type of the variable您可以检查变量的类型

function checkType(input){
     console.log(typeof input)
}


checkType(1234); //number

checkType('Hello') //string

Here is an updated version这是一个更新的版本

function checkType(i){函数 checkType(i){

var input = i.toString(); var input = i.toString(); //convert everything to strings to run .lenght() on it //将所有内容转换为字符串以在其上运行 .lenght()

for(var i=0; i<input.length; ++i){
    if(input[i] >= '0' && input[i] <= '9'){
        console.log(input[i]+' is a number');
    }else if((input[i] >= 'a' && input[i] <= 'z') || (input[i] >= 'A' && input[i] <= 'Z')){
        console.log(input[i]+' is a letter');
    }
  }    
}

checkType('aa9fgg5')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM