Monday, 7 August 2017

Unexpected Result With JavaScript Substr()




I'm having a problem with substr() in JavaScript.

Please look at the code below.




The following works as expected. y = 2017




var add_date = "20170505";
var y = add_date.substr(0, 4);

alert(y);



But... the following doesn't work. It should return '05' but instead it returns 0505. m = 0505




var add_date = "20170505";
var m = add_date.substr(4, 6);
alert(m);



Could someone explain me what's wrong?



Thanks,



Nathan


Answer



.substr(4,6) method returns 6 characters starting at index 4. Use .substring instead.






var add_date = "20170505",
y = add_date.substring(0, 4);
console.log(y);


var add_date = "20170505",
m = add_date.substring(4, 6);
console.log(m);





No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...