SubString() not working the way I expect, why?

R

R

Folks,

Given that ourStr=20091110, I found I can convert the date into
ddmmyyyy using the following function

function convertYYYYMMDD( ourStr )
{
var yyyy=ourStr.substring(0,4);
var mm=ourStr.substring(6,4)
var dd=ourStr.substring(8,6);
return dd+""+mm+""+yyyy;
}

My question is, I believe the syntax is wrong for substring. My
O'Reilly book says

substring(from, to)
Returns a new string that contains characters copied from position
'from' to 'to-1' of 'string'. If to is omitted, the substring extends
to the end of the string.

If this is true, then why do I find dd value is found starting at
position 8, and finishing at position 6 ??? I would expect to be the
reverse (thus, dd=ourString.substring(6,8). And I would expect the
second numeric arg always to be greater than the last since it records
the "to" position.

Is there something I'm not seeing?

thanks

(firefox user)
 
D

Dr J R Stockton

In comp.lang.javascript message <a1f63faf-ec36-4a55-9d73-78888993dbaa@p3
5g2000yqh.googlegroups.com>, Tue, 10 Nov 2009 07:21:47, R
Given that ourStr=20091110, I found I can convert the date into
ddmmyyyy using the following function

function convertYYYYMMDD( ourStr )
{
var yyyy=ourStr.substring(0,4);
var mm=ourStr.substring(6,4)
var dd=ourStr.substring(8,6);
return dd+""+mm+""+yyyy;
}

If you are not paid by the yard of code, you could choose

function convertYYYYMMDD( ourStr ) {
return ourStr.replace(/(....)(..)(..)/, "$3$2$1") }

Any string manipulation using multiple substr or substring with constant
arguments, and many others, can very easily be done with a RegExp.
Simple use of RegExps is sufficiently easy to learn.

In your method, you don't need ""+, twice.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,904
Latest member
HealthyVisionsCBDPrice

Latest Threads

Top