Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert a date format within a string?

I’m looking for a way to replace a date format within a string from "DD.MM.YYY" to "YYYY-MM-DD"

This works fine the input string just contains a date and nothing else:

const input = "19.09.2022";
const converted = input.replace(/^(\d{1,2}).(\d{1,2}).(\d{4})$/, "$3-$2-$1");
console.log(converted) // "2022-09-19"

If the input string contains other strings, the above replace won’t work:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const input = "something here 19.09.2022 another string here";
const converted = input.replace(/^(\d{1,2}).(\d{1,2}).(\d{4})$/, "$3-$2-$1");
console.log(converted) // NOT  "something here 2022-09-19 another string here";

>Solution :

The issue is because your Regex is anchored to the start and end of the string by the ^ and $ characters respectively. If you remove them the search will look through the entire string:

const input = ["19.09.2022", "something here 19.09.2022 another string here"];

input.forEach(str => console.log(str.replace(/(\d{1,2}).(\d{1,2}).(\d{4})/, "$3-$2-$1")));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading