473,725 Members | 2,053 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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.
Jul 23 '05
14 12339


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_NOSPA M_Sowers.com> wrote in message
news:42******** *************** @news.hal-pc.org...

"Christophe r Benson-Manica" <at***@nospam.c yberspace.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=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

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.ne t.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/rasterTriangleD OM.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***@yankeewe b.com>
posted :
String.prototy pe.isdigits=fun ction(){
return (/\D/.test(this)==fa lse);
}


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.
Jul 23 '05 #15

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

Similar topics

0
333
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: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dv_vstechart/html/vbtchaspnetcookies101.asp under section: 'Checking Whether a Browser Accepts Cookies' This code works great, when its in my development enviroment.
14
2947
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 'null-terminated-string' to some functions, such as 'atoi'. (We assume that the string was extracted using an array, not string literal) This program shows blank for '\0' for all 3 cases. Why ? And I was trying to pass some strings formed using an array, without...
4
12720
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 Thanks for ur inputs Anoop
0
1115
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 command line utility, it requires the System.Diagnostics.Process class. It works well enough (code is below), but I was wondering if anyone has a more efficient method. I'm aware that it's
19
8947
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 actually need as a part of one of my project Thank you,
4
12769
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 double-quotes or not inside any quotes? If so how? Thanks in advance: Michael Yanowitz
0
8888
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
1
9174
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9111
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6702
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6011
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4517
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4782
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3221
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2634
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.