Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get ymd by substring with JavaScript

Tags:

javascript

With this code to get ymd:

var ymd = '20190716';
var year = ymd.substring(0, 4);
var month = ymd.substring(4, 2);
var day = ymd.substring(6, 2);

console.log(year);
console.log(month);
console.log(day);

I think its the right way to get substring from index to length. So ...

Want:

2019
07
16

But got:

2019
19
1907

Why?

like image 906
02040402 Avatar asked Dec 31 '22 19:12

02040402


1 Answers

Check the docs:

The substring() method returns the part of the string between the start and end indexes, or to the end of the string.

and

If indexStart is greater than indexEnd, then the effect of substring() is as if the two arguments were swapped.

So when you pass 4, 2 or 6, 2, you're saying that you want the end index to come before the start index, so the arguments get switched, and you get index 2 to 4, and index 2 to 6.

Perhaps you wanted substr, which does what you're expecting:

The arguments of substring() represent the starting and ending indexes, while the arguments of substr() represent the starting index and the number of characters to include in the returned string.

var ymd = '20190716';
var year = ymd.substr(0, 4);
var month = ymd.substr(4, 2);
var day = ymd.substr(6, 2);
console.log(year);
console.log(month);
console.log(day);

But it's (kinda) deprecated. I'd prefer substring or slice, and pass indicies.

The substring() method swaps its two arguments if indexStart is greater than indexEnd, meaning that a string is still returned. The slice() method returns an empty string if this is the case.

slice's behavior is a bit more intuitive IMO.

like image 153
CertainPerformance Avatar answered Jan 11 '23 21:01

CertainPerformance