473,698 Members | 2,668 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 #1
14 12333
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}
Jul 23 '05 #2
Christopher Benson-Manica <at***@nospam.c yberspace.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/rasterTriangleD OM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 23 '05 #3

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


allDigits = str.split(/\d/).length==0
Jul 23 '05 #4
"Vic Sowers" <Mail@Vic_NOSPA M_Sowers.com> writes:
"Christophe r Benson-Manica" <at***@nospam.c yberspace.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.spli t(...) is never 0.
/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 #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_NOSPA M_Sowers.com> writes:
"Christophe r Benson-Manica" <at***@nospam.c yberspace.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.spli t(...) is never 0.


Odd... "1234567890".sp lit(/\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.spli t(...) is never 0.

Odd... "1234567890".sp lit(/\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

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
2943
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
12717
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
1112
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
8944
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
12754
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
8603
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9157
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8861
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
6518
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
5860
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
4615
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3045
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
2327
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
1999
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.