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:
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")));