omega
omega

Reputation: 43833

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 (i.e. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9) or a letter (i.e. A to Z, a to z)?

Thanks

Upvotes: 1

Views: 7155

Answers (5)

mack
mack

Reputation: 112

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

Upvotes: 1

cptdanko
cptdanko

Reputation: 842

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 | Typescript & ES6

Upvotes: 0

plalx
plalx

Reputation: 43718

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).

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.

Upvotes: 2

Geo
Geo

Reputation: 3200

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){

var input = i.toString(); //convert everything to strings to run .lenght() on it

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')

Upvotes: -1

KokaKiwi
KokaKiwi

Reputation: 605

Why not:

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

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

Upvotes: 1

Related Questions