nichijou
nichijou

Reputation: 514

Javascript: split string into strings of specific length

I have a string to parse into Date

const a = '18122122'

and this way(constantly using substr) to parse it is ugly and error-prone

const date = new Date('20' + a.substr(0, 2), a.substr(2, 2) - 1, a.substr(4, 2), a.substr(6,2 ))

Do I miss a method like

const dateArray = a.<method>(2) // return ['18', '12', '21', '22']
dateArray[0] = '20' + dateArray[0]
dateArray[1] -= 1;
const date = new Date(...dateArray)

Upvotes: 1

Views: 139

Answers (2)

user458541
user458541

Reputation:

Try:

const a = "18042019";
let [, day, month, year] = a.match(/^(\d{2})(\d{2})(\d{4})/);
new Date(year, --month, day);

It doesn't matter that the Date arguments are strings containing numbers, as the constructor will typecast each parameter to a Number anyway.

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 371193

You can use a global regular expression to match repeated instances of 2 digits, and then replace the array items as needed:

const a = '18122122';
const dateArray = a.match(/\d{2}/g);
dateArray[0] = '20' + dateArray[0];
dateArray[1] -= 1;
const date = new Date(...dateArray);
console.log(date);

Upvotes: 3

Related Questions