Someone
Someone

Reputation: 10575

Why is the substring method behaving in this manner?

var str ="20110725";
var dd = str.substring(6);
var mm = str.substring(4,2);
var yyyy = str.substring(0,3);
alert(dd );//25
alert(mm);//11
alert(yyyy );//2011

Instead of the above output, I expected "25" as date, "07" as month and "2011" as year. Please correct me.

Upvotes: 1

Views: 161

Answers (4)

Jon Martin
Jon Martin

Reputation: 3392

Instead of:

var mm = str.substring(4, 2)

Do:

var mm = str.substring(4, 6)

Upvotes: 2

JustBeingHelpful
JustBeingHelpful

Reputation: 18980

Try this. You also need a 4, not a 3 for your year.

var str ="20110725";
var dd = str.substr(6);
var mm = str.substr(4,2);
var yyyy = str.substr(0,4);
alert(dd );//25
alert(mm);//11
alert(yyyy );//2011

Upvotes: 1

Paul Sonier
Paul Sonier

Reputation: 39480

You should have

var mm = str.substring(4, 6);

Upvotes: 2

jimbo
jimbo

Reputation: 11042

I think you want substr(), not substring(). They're different.

Upvotes: 3

Related Questions