const regex = /[0-9]{2}\/[0-9]{2}\/[0-9]{4}/gm;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('[0-9]{2}\\\/[0-9]{2}\\\/[0-9]{4}', 'gm')
const str = `Valid dates:
01/04/2020
20/01/2019
25/12/1950
30/07/2021
31/08/1919
01/01/1729
10/05/2000
15/10/2049
Invalid dates:
001/04/1900
01/004/1900
90/04/1900
33/04/1900
01/13/1900
01/04/19000
00/04/1900
01/00/1900
1/4/00
1/04/1900
10/4/1900
10/04/00
///
/04/1900
01//1900
01/04/
01/04/1900
This is the date: 01/04/1900
01.04.1900
01-04-1900
`;
// Reset `lastIndex` if this regex is defined globally
// regex.lastIndex = 0;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for JavaScript, please visit: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions