const regex = /_([_\d]*)[.]/g;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('_([_\\d]*)[.]', 'g')
const str = `myimage_1.jpg
myimage_1_1.jpg
myimage_1_1_1.jpg
myimage_1_1_1_1.jpg
myimage_1_1_1_1_1.jpg
anynumber_1_2_3_4_5_6.jpg
numbers_only_not_text_1.jpg
numbers_only_not_text_1_1.jpg
The '\\d' could purely be replaced with '1' if that is all that is required to be removed.
Ensure to replace matached string with a further '.'`;
// 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