Checking whether a string is all digits

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Christopher Benson-Manica

    Checking whether a string is all digits

    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='123456789 0';
    return nums.indexOf(s) != -1;
    }

    --
    Christopher Benson-Manica | I *should* know what I'm talking about - if I
    ataru(at)cybers pace.org | don't, I need to know. Flames welcome.
  • drWot

    #2
    Re: Checking whether a string is all digits

    String.prototyp e.isdigits=func tion(){
    return (/\D/.test(this)==fa lse);
    }

    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}


    Comment

    • Lasse Reichstein Nielsen

      #3
      Re: Checking whether a string is all digits

      Christopher Benson-Manica <ataru@nospam.c yberspace.org> writes:
      [color=blue]
      > I'm trying to check whether a string is all digits.[/color]

      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 - lrn@hotpop.com
      DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
      'Faith without judgement merely degrades the spirit divine.'

      Comment

      • Vic Sowers

        #4
        Re: Checking whether a string is all digits


        "Christophe r Benson-Manica" <ataru@nospam.c yberspace.org> wrote in message
        news:d828a0$s84 $1@chessie.cirr .com...[color=blue]
        > 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='123456789 0';
        > return nums.indexOf(s) != -1;
        > }
        >
        > --
        > Christopher Benson-Manica | I *should* know what I'm talking about - if I
        > ataru(at)cybers pace.org | don't, I need to know. Flames welcome.[/color]

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


        Comment

        • Lasse Reichstein Nielsen

          #5
          Re: Checking whether a string is all digits

          "Vic Sowers" <Mail@Vic_NOSPA M_Sowers.com> writes:
          [color=blue]
          > "Christophe r Benson-Manica" <ataru@nospam.c yberspace.org> wrote in message
          > news:d828a0$s84 $1@chessie.cirr .com...[color=green]
          >> I'm trying to check whether a string is all digits.[/color][/color]
          ....[color=blue]
          > allDigits = str.split(/\d/).length==0[/color]

          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.spli t(...) is never 0.
          /L
          --
          Lasse Reichstein Nielsen - lrn@hotpop.com
          DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
          'Faith without judgement merely degrades the spirit divine.'

          Comment

          • cosmic fool

            #6
            Re: Checking whether a string is all digits

            you guys are nerds


            Comment

            • Zif

              #7
              Re: Checking whether a string is all digits

              cosmic fool wrote:[color=blue]
              > you guys are nerds
              >
              >[/color]

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

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

              --
              Zif

              Comment

              • cosmic fool

                #8
                Re: Checking whether a string is all digits

                exactly

                "Zif" <zifud@hotmail. com> wrote in message
                news:Pw7pe.1946 $Zn.92056@news. optus.net.au...[color=blue]
                > cosmic fool wrote:[color=green]
                > > you guys are nerds
                > >
                > >[/color]
                >
                > Read the FAQ. Do not top post. Quote what you are replying to.
                >
                > <URL:http://jibbering.com/faq/#FAQ2_3>
                >
                > --
                > Zif[/color]


                Comment

                • Vic Sowers

                  #9
                  Re: Checking whether a string is all digits


                  "Lasse Reichstein Nielsen" <lrn@hotpop.com > wrote in message
                  news:ekbfgmf8.f sf@hotpop.com.. .[color=blue]
                  > "Vic Sowers" <Mail@Vic_NOSPA M_Sowers.com> writes:
                  >[color=green]
                  >> "Christophe r Benson-Manica" <ataru@nospam.c yberspace.org> wrote in
                  >> message
                  >> news:d828a0$s84 $1@chessie.cirr .com...[color=darkred]
                  >>> I'm trying to check whether a string is all digits.[/color][/color]
                  > ...[color=green]
                  >> allDigits = str.split(/\d/).length==0[/color]
                  >
                  > 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.spli t(...) is never 0.[/color]

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


                  Comment

                  • RobG

                    #10
                    Re: Checking whether a string is all digits

                    Vic Sowers wrote:
                    [...][color=blue][color=green]
                    >>Either do:
                    >>
                    >> var allDigits = (str.split(/\d/).length == (str.length+1)) ;
                    >>
                    >>or
                    >>
                    >> var allDigits = (str.split(/\D/).length <= 1);
                    >>
                    >>The length of someString.spli t(...) is never 0.[/color]
                    >
                    >
                    > Odd... "1234567890".sp lit(/\d/).length is 0 in IE and 11 in Firefox.
                    >
                    >[/color]

                    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

                    Comment

                    • cwdjrxyz@yahoo.com

                      #11
                      Re: Checking whether a string is all digits



                      Christopher Benson-Manica wrote:[color=blue]
                      > I'm trying to check whether a string is all digits.[/color]

                      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.

                      Comment

                      • Stephen Chalmers

                        #12
                        Re: Checking whether a string is all digits

                        Vic Sowers <Mail@Vic_NOSPA M_Sowers.com> wrote in message
                        news:42a4beab$0 $64582$a726171b @news.hal-pc.org...[color=blue]
                        >
                        > "Christophe r Benson-Manica" <ataru@nospam.c yberspace.org> wrote in[/color]
                        message[color=blue]
                        > news:d828a0$s84 $1@chessie.cirr .com...[/color]
                        [color=blue][color=green]
                        > > var foo=str.split( '' ); // better than charAt()?[/color][/color]

                        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=fals e;

                        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.lengt h)
                        justDigits=true ;
                        }
                        return justDigits;
                        }


                        --
                        Stephen Chalmers
                        547265617375726 520627572696564 206174204F2E532 E207265663A2054 5132343739
                        3134



                        Comment

                        • Michael Winter

                          #13
                          Re: Checking whether a string is all digits

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

                          [snip]
                          [color=blue]
                          > Try this:
                          >
                          > alert( "".split(/\d/).length );
                          > alert( "1".split(/\d/).length );
                          >
                          > Firefox reports: 1 then 2, but IE reports 1 then 0.[/color]

                          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', ''.
                          [color=blue]
                          > Explain that and keep a straight face.[/color]

                          Not a straight face. More one of resigned expectation.

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

                          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.

                          Comment

                          • Lasse Reichstein Nielsen

                            #14
                            Re: Checking whether a string is all digits

                            RobG <rgqld@iinet.ne t.auau> writes:
                            [color=blue]
                            > 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.[/color]

                            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).
                            [color=blue]
                            > Here's another:
                            >
                            > y = [ ]; alert(y.length) // Both browsers say 0
                            > y = [ ,,, ]; alert(y.length) // Firefox says 3, IE says 4[/color]

                            Again IE fails to satisfy the ECMAScript standard. Firefox is correct.
                            [color=blue]
                            > If the last element is undefined, Firefox doesn't add it to the array.[/color]

                            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 - lrn@hotpop.com
                            DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
                            'Faith without judgement merely degrades the spirit divine.'

                            Comment

                            • Dr John Stockton

                              #15
                              Re: Checking whether a string is all digits

                              JRS: In article <mJ1pe.891$2H2. 647@trndny08>, dated Mon, 6 Jun 2005
                              19:45:22, seen in news:comp.lang. javascript, drWot <drwot@yankeewe b.com>
                              posted :
                              [color=blue]
                              >String.prototy pe.isdigits=fun ction(){
                              > return (/\D/.test(this)==fa lse);
                              >}[/color]

                              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.c om/faq/> JL/RC: FAQ of news:comp.lang. javascript
                              <URL:http://www.merlyn.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
                              <URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.

                              Comment

                              Working...