我有这个字符串:
var case1 = '5.25 - 12.25, 13 - 18.5';
var case2 = '6.5 - 12, 13 - 18.5';
var case3 = '9 - 13, 14 - 18';
我需要将它们转换为:
result1; //05:15 - 12:15, 13:00 - 18:30;
result2; //06:30 - 12:00, 13:00 - 18:30;
result3; //09:00 - 13:00, 14:00 - 18:00;
是否可以只使用正则表达式?
规则:
1)如果数字小于10,则添加前导0
2)将.25
替换为:15
,将.5
替换为:30
3)如果该点之后没有任何内容,请添加00
我尝试用条件,替换等来做它,但它很乱。
答案 0 :(得分:3)
您可以使用一个正则表达式,但使用replace
回调函数:
const cases = [
'5.25 - 12.25, 13 - 18.5',
'6.5 - 12, 13 - 18.5',
'9 - 13, 14 - 18'
];
const result = cases.map( c => c.replace(/(\d+)(\.\d+)?/g, (_, h, m) =>
('0'+h).substr(-2) + ':' + ('0' + (Math.floor(m*60) || 0)).substr(-2)
));
console.log(result);

var cases = [
'5.25 - 12.25, 13 - 18.5',
'6.5 - 12, 13 - 18.5',
'9 - 13, 14 - 18'
];
var result = cases.map(function (c) {
return c.replace(/(\d+)(\.\d+)?/g, function (_, h, m) {
return ('0'+h).substr(-2) + ':' + ('0' + (Math.floor(m*60) || 0)).substr(-2);
});
});
console.log(result);

答案 1 :(得分:1)
非正则表达式解决方案:
const cases = [
'5.25 - 12.25, 13 - 18.5',
'6.5 - 12, 13 - 18.5',
'9 - 13, 14 - 18'
];
const result = cases.map( c =>
c.split(", ").map(range =>
range.split(" - ").map(time => {
const [hours,mins] = time.split(".");
return ("00"+hours).substr(-2)+":"+(Math.floor( mins*6/10 ) || "00");
}).join(" - ")
).join(", ")
);
答案 2 :(得分:1)
var cases = ['5.25 - 12.25, 13 - 18.5',
'6.5 - 12, 13 - 18.5',
'9 - 13, 14 - 18'];
cases.forEach(function(src){
var times = src.replace(/([\d\.])+/g,function(match){
var seconds = match*60;
var minutes = parseInt(seconds/60);
var seconds = "00" + seconds%60;
seconds = seconds.substr(seconds.length-2);
return minutes+":"+seconds;
});
console.log(times);
});