You can use a pattern which matches either the date pattern or anything else, up until the start of a date pattern (or the end of the string). Then use a replacer function. If the match is the same format as the date, replace with the entire match (thereby leaving the string unchanged there). Otherwise, replace with whatever you need.
const str = 'Hey how 30.01.2019 are you 23.05.2020 I am fine.';
const datePatternStr = String.raw`(?:[0-2]\d|3[01])\.(?:0\d|1[0-2])\.(?:\d{4}|\d{2})`;
const datePattern = new RegExp(datePatternStr);
const result = str.replace(
new RegExp(`${datePatternStr}|.+?(?=$|${datePatternStr})`, 'g'),
(match) => {
if (datePattern.test(match)) return match;
return 'foo bar';
}
);
console.log(result);
The constructed pattern:
${datePatternStr}|.+?(?=$|${datePatternStr})
means:
${datePatternStr}
- Match the date pattern, or:
.+?(?=$|${datePatternStr})
- Match:
.+?
One or more characters, as few as possible, up until lookahead matches:
$
either the end of the string, or
- datePatternStr
Note that you can trim your original pattern down to:
(?:[0-2]\d|3[01])\.(?:0\d|1[0-2])\.(?:\d{4}|\d{2})
(only use groups when they're required for the logic you need, \d
can be used instead of [0-9]
, and only use capturing groups when non-capturing groups won't suffice)