RegEx for flexible time checking in JavaScript
I started with a regex to check the time, it should detect strings like:
5s
3h5m
5h3m02s
05:03:02
05:03
4
My current regex is valid for all of them, but one: 05:03 . It detects 05 as hours and 03 as seconds, but it should be 05 as minutes ... and I don't know how to edit my code to do this.
var reTime =
/^(?:PT)?(?:(\d{1,2})[:.hH])?(?:(\d{1,4})[:.mM])?(?:(\d{1,6})[sS]?)?$/;
+3
source to share
1 answer
Check it:
var hasTimeFormat = function (input) {
var timeFormat = /([0-9]{2})\:([0-9]{2})\:([0-9]{2})\,([0-9]{3})$/;
if (typeof String.prototype.trim !== 'function') {
String.prototype.trim = function () {
return input.replace(/^\s+|\s+$/g, '');
}
}
return timeFormat.test(input.trim());
}
This works well (for example for "05: 03: 02.677"), and if you want to add something else, you can easily add.
-1
source to share