Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
24
rated 0 times [  26] [ 2]  / answers: 1 / hits: 19771  / 14 Years ago, fri, october 1, 2010, 12:00:00

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.


More From » regex

 Answers
83

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;
}

[#95438] Wednesday, September 29, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
donaldcristianl

Total Points: 114
Total Questions: 95
Total Answers: 110

Location: Bonaire
Member since Sat, May 27, 2023
1 Year ago
;