Monday, May 28, 2018

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

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...