Checking whether a string is all digits

  • Thread starter Christopher Benson-Manica
  • Start date
C

Christopher Benson-Manica

I'm trying to check whether a string is all digits. This part is
easy:

function allDigits( str ) {
var foo=str.split( '' ); // better than charAt()?
for( var idx=0; idx < foo.length; idx++ ) {
if( !isDigit(foo[idx]) ) {
return false;
}
}
return true;
}

I'm not sure about how to implement isDigit(). Is this the best way?

function isDigit( s ) {
if( s.length > 1 ) {
return false;
}
var nums='1234567890';
return nums.indexOf(s) != -1;
}
 
D

drWot

String.prototype.isdigits=function(){
return (/\D/.test(this)==false);
}

This returns true if there are no non-digits in the string.
Since it is a prototype method, call it for a string str like this:

if(str.isdigits()){do something}
else {do something else}
 
L

Lasse Reichstein Nielsen

Christopher Benson-Manica said:
I'm trying to check whether a string is all digits.

For that, regular expressions is the simplest way, by some orders
of magnitude :)

function allDigits(str) {
return /^\d*$/.test(str); // consists of only digits from start to end
}

or even:

function allDigits(str) {
return !/\D/.test(str); // doesn't contain non-digit
}

This accepts the empty string, which is, technically, all digits
(there is nothing but digits). If you want only non-empty strings,
change it to:

function allDigits(str) {
return /^\d+$/.test(str);
}


Good luck.
/L
 
V

Vic Sowers

Christopher Benson-Manica said:
I'm trying to check whether a string is all digits. This part is
easy:

function allDigits( str ) {
var foo=str.split( '' ); // better than charAt()?
for( var idx=0; idx < foo.length; idx++ ) {
if( !isDigit(foo[idx]) ) {
return false;
}
}
return true;
}

I'm not sure about how to implement isDigit(). Is this the best way?

function isDigit( s ) {
if( s.length > 1 ) {
return false;
}
var nums='1234567890';
return nums.indexOf(s) != -1;
}

allDigits = str.split(/\d/).length==0
 
L

Lasse Reichstein Nielsen

Vic Sowers said:
....
allDigits = str.split(/\d/).length==0

Test your code :)

Either do:

var allDigits = (str.split(/\d/).length == (str.length+1));

or

var allDigits = (str.split(/\D/).length <= 1);

The length of someString.split(...) is never 0.
/L
 
V

Vic Sowers

Lasse Reichstein Nielsen said:
Test your code :)

Either do:

var allDigits = (str.split(/\d/).length == (str.length+1));

or

var allDigits = (str.split(/\D/).length <= 1);

The length of someString.split(...) is never 0.

Odd... "1234567890".split(/\d/).length is 0 in IE and 11 in Firefox.
 
R

RobG

Vic Sowers wrote:
[...]
Odd... "1234567890".split(/\d/).length is 0 in IE and 11 in Firefox.

You think that's weird? Try this:

alert( "".split(/\d/).length );
alert( "1".split(/\d/).length );


Firefox reports: 1 then 2, but IE reports 1 then 0. Explain that and
keep a straight face.

Using a letters rather than a digits gives exactly the same result.

alert( "".split(/\w/).length );
alert( "a".split(/\w/).length );

Firefox: 1 then 2, IE: 1 then 0.

Here's another:

y = [ ]; alert(y.length) // Both browsers say 0
y = [ ,,, ]; alert(y.length) // Firefox says 3, IE says 4
y = [ ,,,'' ]; alert(y.length) // Firefox says 4, IE says 4

If the last element is undefined, Firefox doesn't add it to the array.

One or the other has got to be in error. Bottom line: be very careful
when building arrays.
 
C

cwdjrxyz

Christopher said:
I'm trying to check whether a string is all digits.

There likely are several ways to do it. I made a test page for you at
my site at http://www.cwdjr.info/test/detectNonNumerical.html . I have
used this method on a perpetual calendar page of mine, and it has
worked on several of the most recent browsers. I detect if the number
is too large and too small as well as check for a negative number. It
is easy to dump these extras if you are interested only in digits.
 
S

Stephen Chalmers

Actally it isn't. charAt() gives access to individual characters in an
existing string, so why build a new array to do the same thing? Rather
than searching for the character in a string of all characters, check
that its value is within range (which is what the RegExp engine will
do, only much faster).

function allDigits( str )
{
var justDigits=false;

if(typeof str!='undefined' && str.length)
{
for( var i=0, d ; i<str.length && (d=str.charAt(i))>='0' &&
d<='9' ; i++ )
;
if(i==str.length)
justDigits=true;
}
return justDigits;
}
 
D

Dr John Stockton

JRS: In article <mJ1pe.891$2H2.647@trndny08>, dated Mon, 6 Jun 2005
String.prototype.isdigits=function(){
return (/\D/.test(this)==false);
}

There is no need to use ==false; return !/\D/.test(this) .

That accepts an empty string.
 
M

Michael Winter

On 07/06/2005 08:07, RobG wrote:

[snip]
Try this:

alert( "".split(/\d/).length );
alert( "1".split(/\d/).length );

Firefox reports: 1 then 2, but IE reports 1 then 0.

As usual, IE is broken.

The character class escape, \d, cannot match an empty string, so the
return value should be an array that contains one element: the empty
string. If a pattern can match the empty string (for example, \d|), then
the result should be an array with zero elements.

The character class escape, \d, can match the digit, 1. Therefore the
result, in this particular case, should be an array that contains two
elements. The first is all of the characters from the start of the
string to just before the matched digit (an empty string), and all of
the characters after the matched digit to the end of the string (again,
an empty string).

If the second regular expression captured the digit, (\d), the resulting
array would have three elements: '', '1', ''.
Explain that and keep a straight face.

Not a straight face. More one of resigned expectation.

[snip]
y = [ ,,, ]; alert(y.length) // Firefox says 3, IE says 4
y = [ ,,,'' ]; alert(y.length) // Firefox says 4, IE says 4

Again, IE is wrong. Each elision (just a comma; no value) increments the
length of the array. In the first literal, there are three elisions so
the length is three. In the second literal there are also three
elisions, however the string literal is appended to the array[1],
creating the fourth element.

[snip]

Mike


[1] That's not how the specification describes it, but it's the same
result.
 
L

Lasse Reichstein Nielsen

RobG said:
You think that's weird? Try this:

alert( "".split(/\d/).length );
alert( "1".split(/\d/).length );

Firefox reports: 1 then 2, but IE reports 1 then 0. Explain that and
keep a straight face.

IE is wrong. Hard not to say that with a straight face. :)

It seems IE removes initial/terminal empty parts, if it does any split
at all.

I was wrong too. It is possible to get a zero-length result out of split:
"".split(/.?/);
(the empty string with a pattern that matches a zero-length string).
Here's another:

y = [ ]; alert(y.length) // Both browsers say 0
y = [ ,,, ]; alert(y.length) // Firefox says 3, IE says 4

Again IE fails to satisfy the ECMAScript standard. Firefox is correct.
If the last element is undefined, Firefox doesn't add it to the array.

No, it's not that there is an element that is undefined. The "," sequence
is an "elision" in the grammar of array literals, and a different token
than the one for actual elements.

/L
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top