const regex = /(\+|\-)?(\d{1,})(?:\s|)(ms|millisecond(?:\(s\)|s|)|second(?:\(s\)|s|)|sec|s(?:\s|$)|minute(?:\(s\)|s|)|min|m(?:\s|$)|h(?:\s|$)|hour(?:\(s\)|s|)|h(?:\s|$)|day(?:\(s\)|s|)|d(?:\s|$)|week(?:\(s\)|s|)|w(?:\s|$)|month(?:\(s\)|s|)|mm(?:\s|$)|year(?:\(s\)|s|)|y(?:\s|$))(?:\s|$)?/gim;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('(\\+|\\-)?(\\d{1,})(?:\\s|)(ms|millisecond(?:\\(s\\)|s|)|second(?:\\(s\\)|s|)|sec|s(?:\\s|$)|minute(?:\\(s\\)|s|)|min|m(?:\\s|$)|h(?:\\s|$)|hour(?:\\(s\\)|s|)|h(?:\\s|$)|day(?:\\(s\\)|s|)|d(?:\\s|$)|week(?:\\(s\\)|s|)|w(?:\\s|$)|month(?:\\(s\\)|s|)|mm(?:\\s|$)|year(?:\\(s\\)|s|)|y(?:\\s|$))(?:\\s|$)?', 'gim')
const str = `+1ms
+19milliseconds
+7 milliseconds
-1 millisecond
+7 s
+8 s
+4 seconds
-1 second
+10 minutes
+1A minutes
-1 minute
+1m
-1m
+1 m
-2 m
1 more time
1min
1 min
+19 hours
-1 hour
+1h
-1h
+1 h
-2 h
+1 day(s)
+2 week(s)
+3mm
+3 month(s)
+4 year(s)
1ms
public Myles +1 minute
Porter Robinson & Madeon - Shelter - Acapella Cover
haha xd +4 years lol`;
// 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