Can someone suggest me a better way of matching a year in a string between the provided ranges.
A better (shorter) way than this:
let str = 'Document created in 1999';
let str1 = 'Document created in 2000';
let str2 = 'Document created in 2001';
let str_r = str.replaceAll(/[0-9][0-9][0-9][0-9]/ig, '2022');
let str_r1 = str1.replaceAll(/[0-9][0-9][0-9][0-9]/ig, '2023');
let str_r2 = str2.replaceAll(/[0-9][0-9][0-9][0-9]/ig, '2024');
console.log('str', str_r);
console.log('str1', str_r1);
console.log('str2', str_r2);
Any insight will be appreciated.
Example String
let str = 'Document created in 1999';
let str1 = 'Document created in 2000';
let str2 = 'I was created in 2001';
2
Answers
As I mentioned in a comment, I don’t think a single regex is the best way to do this, but here is a regex matching all years from 1999 to 2024 inclusive.
Better would be to loop over all the years and avoid the potential regex errors altogether.
Use a regex with 4 digits between word boundaries and a replacement callback function that checks the year range: