I'm catching the date from a form as a string and pass it to a API-Request-URL.
The date string is in this format: 16022019 But the API accepts a date string only in this format: 20190216.
Basically, in my string, I need to change the position of the first 2 characters with the position of the last 4 characters.
I fixed the issue as follow:
let date = e.target.elements.date.value; // 16022019
const dateFirst = date.slice(0, 2);
const dateMiddle = date.slice(2, 4);
const dateLast = date.slice(4, 8);
date = `${dateLast}${dateMiddle}${dateFirst}`; // 20190216
But I'm not sure if this is a good solution. Is there any better way to achieve the same result?
I don't see any problem with your method. in case you want to know alternate you can try this.
This uses regex to capture digits of desired width and than places to desired place.
let str = `16022019`
console.log(str.replace(/(\d{2})(\d{2})(\d{4})/,"$3$2$1"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With