87,922
社区成员
发帖
与我相关
我的任务
分享
<input id="time" value="03:00-06:00 07:30-08:40 09:10-10:10 6:0-06:50" style="width:500px;" />
<input type="button" id="click" value="测试" />
<script type="text/javascript">
document.getElementById('click').onclick = function () {
var ps = '(?:2[0-3]|[01]?[0-9]):[0-5]?[0-9]-(?:2[0-3]|[01]?[0-9]):[0-5]?[0-9]';
var pattern = new RegExp('^[\\s\\u3000\\xA0]*' + ps + '(?:[\\s\\u3000\\xA0]+' + ps + ')*[\\s\\u3000\\xA0]*$');
var spattern = /\b(2[0-3]|[01]?[0-9]):([0-5]?[0-9])-(2[0-3]|[01]?[0-9]):([0-5]?[0-9])\b/g;
var time = document.getElementById('time');
var ary = [], a, b;
if (pattern.test(time.value)) {
while (spattern.test(time.value)) {
//稍微排序下
a = 1 * ((RegExp.$1 * 100).toString().slice(0, 4) * 1 + RegExp.$2 * 1), b = 1 * ((RegExp.$3 * 100).toString().slice(0, 4) * 1 + RegExp.$4 * 1);
ary.push(a <= b ? [a, b] : [b, a]);
}
ary.sort(function (a, b) { return a[0] - b[0]; }); //排序
for (var i = 1, l = ary.length ; i < l ; i ++) { //判断交
if (ary[i - 1][1] > ary[i][0]) {
alert('不允许交集');
}
}
ary = ary.toString().split(',');
for (var i = 0, l = l * 2, s = [] ; i < l ; i ++) {
//补0并还原数据
if (ary[i] * 1 < 1000) ary[i] = '0' + ary[i];
ary[i] = ary[i].split(/(?=.{2}$)/).join(':');
if (i % 2 > 0) s.push(ary[i - 1] + '-' + ary[i]);
}
time.value = s.join('\xA0');
//返回排序后的并且补0的结果
} else {
alert('数据不合法');
time.focus();
time.select();
}
}
</script>