skip to Main Content

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


  1. 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.

    let re = /1999|20[01]d|202[0-4]/gi;
    let str = "Goodbye 1999, hello 2000!"
    let newstr = str.replaceAll(re, "new");
    console.log(newstr); // Goodbye new, hello new!
    

    Better would be to loop over all the years and avoid the potential regex errors altogether.

    let str = "Goodbye 1999, hello 2000!"
    for (let i = 1999; i <= 2024; i++) {
      str = str.replace(i.toString(), "new");
    }
    console.log(str); // Goodbye new, hello new!
    
    Login or Signup to reply.
  2. Use a regex with 4 digits between word boundaries and a replacement callback function that checks the year range:

    let str = 'Document created in 1999';
    let str1 = 'Document created in 2000';
    let str2 = 'Document created in 2001';
    let str3 = 'Document created in 1998-2008 with 19999 characters';
    
    
    [str, str1, str2, str3].forEach(str => console.log(
      str.replace(/(?<=b)d{4}(?=b)/g, year => year >= 1999 && year <= new Date().getFullYear() ? '[replacement]' : year)
    ));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search