Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing order of characters in a string using JavaScript

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?

like image 463
user1941537 Avatar asked Oct 17 '25 10:10

user1941537


1 Answers

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"))
like image 197
Code Maniac Avatar answered Oct 20 '25 00:10

Code Maniac



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!