473,395 Members | 1,656 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

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='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.
Jul 23 '05 #1
14 12293
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}
Jul 23 '05 #2
Christopher Benson-Manica <at***@nospam.cyberspace.org> 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 - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 23 '05 #3

"Christopher Benson-Manica" <at***@nospam.cyberspace.org> wrote in message
news:d8**********@chessie.cirr.com...
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
Jul 23 '05 #4
"Vic Sowers" <Mail@Vic_NOSPAM_Sowers.com> writes:
"Christopher Benson-Manica" <at***@nospam.cyberspace.org> wrote in message
news:d8**********@chessie.cirr.com...
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 - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 23 '05 #5
you guys are nerds
Jul 23 '05 #6
Zif
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
Jul 23 '05 #7
exactly

"Zif" <zi***@hotmail.com> wrote in message
news:Pw*****************@news.optus.net.au...
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

Jul 23 '05 #8

"Lasse Reichstein Nielsen" <lr*@hotpop.com> wrote in message
news:ek**********@hotpop.com...
"Vic Sowers" <Mail@Vic_NOSPAM_Sowers.com> writes:
"Christopher Benson-Manica" <at***@nospam.cyberspace.org> wrote in
message
news:d8**********@chessie.cirr.com...
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.
Jul 23 '05 #9
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
Jul 23 '05 #10


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.

Jul 23 '05 #11
Vic Sowers <Mail@Vic_NOSPAM_Sowers.com> wrote in message
news:42***********************@news.hal-pc.org...

"Christopher Benson-Manica" <at***@nospam.cyberspace.org> wrote in message news:d8**********@chessie.cirr.com...

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
547265617375726520627572696564206174204F2E532E2072 65663A20545132343739
3134

Jul 23 '05 #12
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.
Jul 23 '05 #13
RobG <rg***@iinet.net.auau> 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 - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 23 '05 #14
JRS: In article <mJ1pe.891$2H2.647@trndny08>, dated Mon, 6 Jun 2005
19:45:22, seen in news:comp.lang.javascript, drWot <dr***@yankeeweb.com>
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.
Jul 23 '05 #15

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Lucifer | last post by:
Hi I have some code for checking for cookies, that sets a cookie on page1 and checks for it on page2. and its based on the code by MS: ...
14
by: Kayle | last post by:
How should we check if the '\0' characters exists in the string as I am confused that some books mentioned that we have to check whether we need to make sure that we pass the...
4
by: Anoop | last post by:
Hi All I am getting two different outputs when i do an operation using string.digits and test.isdigit(). Is there any difference between the two. I have given the sample program and the output ...
0
by: Mark Rae | last post by:
Hi, For years I've been using the clwhois.exe app to check whether domains are available or not and, if not, who owns them: http://www.whoisview.com/products/clwhois/ Because this is a...
19
by: SPABBOJU | last post by:
Hi guys... I want to check whether string does not exist with out using !~ . basical for character we check like that using . How to do the same for word, sentence ?.... I...
4
by: Michael Yanowitz | last post by:
Hello: If I have a long string (such as a Python file). I search for a sub-string in that string and find it. Is there a way to determine if that found sub-string is inside single-quotes or...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.