AndreaNobili
AndreaNobili

Reputation: 42967

Why I have this error trying to use the JavaScript substr() function?

I am absolutly new in JavaScript and I have the following problem trying to use the substr() method.

I have a string that represent a data: 20141202 (that is for 2014-12-02 without the '-' character).

So my DataDA variable contains the value 20141202

Now I want to extract the year, the month and the day from this string and I have done something like this:

year = DataDA.substr(0,4); 

and this seems work fine because year value is 2014

But when I try to extract the month I have a very strange behavior, infact I do:

month = DataDA.substr(5,6); 

and instead obtain 12 I obtain 202

Why? What am I missing?

Upvotes: 0

Views: 131

Answers (4)

kjexley
kjexley

Reputation: 317

You need to change it to:

 month = DataDA.substr(4,2);

The 1st number defines the starting number and the second defines the length of the string.

Upvotes: 1

Because

function substr(start,lenght)

you can use like this,

var DataDA = 20142201;

var year = DataDA.toString().substr(0,4); 

var day = DataDA.toString().substr(4,2); 

var month = DataDA.toString().substr(6,2); 

Upvotes: 1

Miknash
Miknash

Reputation: 7948

First parameter is from which index are you going and second one is how much do you want to go.

So you need

month = DataDA.substr(4,2); 

Upvotes: 1

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79830

The second argument in .substr(start[, length]) is length to extract. You can either use length as 2 to .substr or use .substring which uses index.

alert("20141202".substr(4,2));

Upvotes: 2

Related Questions