Checking whether a string is all digits

Discussion in 'Javascript' started by Christopher Benson-Manica, Jun 6, 2005.

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

    --
    Christopher Benson-Manica | I *should* know what I'm talking about - if I
    ataru(at)cyberspace.org | don't, I need to know. Flames welcome.
     
    Christopher Benson-Manica, Jun 6, 2005
    #1
    1. Advertising

  2. Christopher Benson-Manica

    drWot Guest

    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}
     
    drWot, Jun 6, 2005
    #2
    1. Advertising

  3. Christopher Benson-Manica <> writes:

    > 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
    --
    Lasse Reichstein Nielsen -
    DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
    'Faith without judgement merely degrades the spirit divine.'
     
    Lasse Reichstein Nielsen, Jun 6, 2005
    #3
  4. Christopher Benson-Manica

    Vic Sowers Guest

    "Christopher Benson-Manica" <> wrote in message
    news:d828a0$s84$...
    > 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;
    > }
    >
    > --
    > Christopher Benson-Manica | I *should* know what I'm talking about - if I
    > ataru(at)cyberspace.org | don't, I need to know. Flames welcome.


    allDigits = str.split(/\d/).length==0
     
    Vic Sowers, Jun 6, 2005
    #4
  5. "Vic Sowers" <Mail@Vic_NOSPAM_Sowers.com> writes:

    > "Christopher Benson-Manica" <> wrote in message
    > news:d828a0$s84$...
    >> I'm trying to check whether a string is all digits.

    ....
    > 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
    --
    Lasse Reichstein Nielsen -
    DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
    'Faith without judgement merely degrades the spirit divine.'
     
    Lasse Reichstein Nielsen, Jun 6, 2005
    #5
  6. Christopher Benson-Manica

    cosmic fool Guest

    you guys are nerds
     
    cosmic fool, Jun 6, 2005
    #6
  7. Christopher Benson-Manica

    Zif Guest

    cosmic fool wrote:
    > you guys are nerds
    >
    >


    Read the FAQ. Do not top post. Quote what you are replying to.

    <URL:http://jibbering.com/faq/#FAQ2_3>

    --
    Zif
     
    Zif, Jun 7, 2005
    #7
  8. Christopher Benson-Manica

    cosmic fool Guest

    exactly

    "Zif" <> wrote in message
    news:pw7pe.1946$...
    > cosmic fool wrote:
    > > you guys are nerds
    > >
    > >

    >
    > Read the FAQ. Do not top post. Quote what you are replying to.
    >
    > <URL:http://jibbering.com/faq/#FAQ2_3>
    >
    > --
    > Zif
     
    cosmic fool, Jun 7, 2005
    #8
  9. Christopher Benson-Manica

    Vic Sowers Guest

    "Lasse Reichstein Nielsen" <> wrote in message
    news:...
    > "Vic Sowers" <Mail@Vic_NOSPAM_Sowers.com> writes:
    >
    >> "Christopher Benson-Manica" <> wrote in
    >> message
    >> news:d828a0$s84$...
    >>> I'm trying to check whether a string is all digits.

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


    Odd... "1234567890".split(/\d/).length is 0 in IE and 11 in Firefox.
     
    Vic Sowers, Jun 7, 2005
    #9
  10. Christopher Benson-Manica

    RobG Guest

    Vic Sowers wrote:
    [...]
    >>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.
    >
    >


    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.



    --
    Rob
     
    RobG, Jun 7, 2005
    #10
  11. Christopher Benson-Manica

    Guest

    Christopher Benson-Manica wrote:
    > 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.
     
    , Jun 7, 2005
    #11
  12. Vic Sowers <Mail@Vic_NOSPAM_Sowers.com> wrote in message
    news:42a4beab$0$64582$-pc.org...
    >
    > "Christopher Benson-Manica" <> wrote in

    message
    > news:d828a0$s84$...


    > > var foo=str.split( '' ); // better than charAt()?


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


    --
    Stephen Chalmers
    547265617375726520627572696564206174204F2E532E207265663A20545132343739
    3134
     
    Stephen Chalmers, Jun 7, 2005
    #12
  13. JRS: In article <mJ1pe.891$2H2.647@trndny08>, dated Mon, 6 Jun 2005
    19:45:22, seen in news:comp.lang.javascript, drWot <>
    posted :

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

    --
    © John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
    <URL:http://www.jibbering.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
    <URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
    <URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
     
    Dr John Stockton, Jun 7, 2005
    #13
  14. 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.

    --
    Michael Winter
    Replace ".invalid" with ".uk" to reply by e-mail.
     
    Michael Winter, Jun 7, 2005
    #14
  15. RobG <> writes:

    > 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
    --
    Lasse Reichstein Nielsen -
    DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
    'Faith without judgement merely degrades the spirit divine.'
     
    Lasse Reichstein Nielsen, Jun 7, 2005
    #15
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Brad Smith
    Replies:
    2
    Views:
    482
    Blaise Pascal Tine
    Jun 27, 2003
  2. Jonck
    Replies:
    3
    Views:
    2,385
    Jonck
    Oct 25, 2004
  3. Dan Pop

    Re: Checking for hexadecimal digits

    Dan Pop, Jul 30, 2003, in forum: C Programming
    Replies:
    8
    Views:
    324
    Neil Cerutti
    Jul 31, 2003
  4. Kayle
    Replies:
    14
    Views:
    577
    MikeyD
    Sep 16, 2003
  5. Peter Bunyan
    Replies:
    9
    Views:
    139
    Lloyd Linklater
    Nov 23, 2007
Loading...

Share This Page