Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript, best way to tell if a val is a single digit

whats the best way to tell if a value in javascript is a single digit. Ive been doing something like

var valAsString = '' + val;
if (valAsString.match(/\d/) {}

clarification: I mean one of 0,1,2,3,4,5,6,7,8,9

Also, should what I have work? Im surprised how many different ways people are coming up with for this.

like image 737
hvgotcodes Avatar asked Dec 05 '22 01:12

hvgotcodes


2 Answers

The /\d/ regexp will match a digit anywhere on a string, for example in "foo1" will match "1".

For a regexp approach need something like this, to ensure that the string will contain a single digit:

if (/^\d$/.test(val))  {
  //..
}

Note that I'm using the test method, which is recommended when you only want to check if a string matches the pattern, also, the test method internally will convert to sting the argument.

Another short non-regexp approach:

function isDigit(val) {
  return String(+val).charAt(0) == val;
}
like image 107
Christian C. Salvadó Avatar answered Dec 27 '22 14:12

Christian C. Salvadó


Ummm, check if it's string length is equal to one?

if (typeof(val) === "number")
    {
    var valAsString = val.toString(10);
    if (valAsString.length === 1) {}
    }

This won't accept negative numbers or numbers with decimal components though.

like image 45
Randy the Dev Avatar answered Dec 27 '22 12:12

Randy the Dev