Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

A bug in substr ?? 1

Status
Not open for further replies.

Trusts

Programmer
Joined
Feb 23, 2005
Messages
268
Location
US
Hi all,

Following is some code. Please run this and see if you get the same result I am getting.

Note that there are four snippets. In each the birthdate is incremented by one, starting with Dec. 6 and going to Dec. 9 (12091995).

For each snippet are two alerts. The first shows substr(2,2). The second shows the parse integer of substr. 8 messages are displayed. I get

06
6
07
7
08
0
09
0

The issue - 08 and 09 are not treated the same as 06 and 07 (or as 05, 04, etc.). Anyone know why this happens? Is this a bug in javascript? Here is the code:


<HTML>
<HEAD>
<TITLE></TITLE>
<Script Type="text/javascript">

function test1()
{

var birthdate1="12061995"
alert (birthdate1.substr(2,2))
dd1=parseInt(birthdate1.substr(2,2))
alert (dd1)

var birthdate2="12071995"
alert (birthdate2.substr(2,2))
dd2=parseInt(birthdate2.substr(2,2))
alert (dd2)


var birthdate3="12081995"
alert (birthdate3.substr(2,2))
dd3=parseInt(birthdate3.substr(2,2))
alert (dd3)


var birthdate4="12091995"
alert (birthdate4.substr(2,2))
dd4=parseInt(birthdate4.substr(2,2))
alert (dd4)

}
</Script>
</HEAD>
<BODY BGCOLOR="#EBEEEE">
<input type="button" onclick="test1()" value="Click" />
</BODY>
</HTML>


 
Not a bug - just bad implementation on your part. You've missed off the base param in parseInt:

Code:
var xxx = parseInt(num[!], 10[/!]);

Hope this helps,
Dan



Coedit Limited - Delivering standards compliant, accessible web solutions

[tt]Dan's Page [blue]@[/blue] Code Couch
[/tt]
 
Per [link: ]w3schools javascript ref[/url],

If the radix parameter is omitted, JavaScript assumes the following:

* If the string begins with "0x", the radix is 16 (hexadecimal)
* If the string begins with "0", the radix is 8 (octal). This feature is deprecated
* If the string begins with any other value, the radix is 10 (decimal)

Since your strings begin with "0", but 8 and 9 are invalid octal digits, you get 0.

Change all of your calls to the form:
Code:
parseInt(birthdate1.substr(2,2),10)
and you should be fine.

IBM Certified Advanced Technical Expert pSeries and AIX 5L
CompTIA Linux+
CompTIA Security+

A Simple Code for Posting on the Web
 
Guess you should have provided a link, Dan.....

-kaht

Lisa, if you don't like your job you don't strike. You just go in every day and do it really half-assed. That's the American way. - Homer Simpson
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top