在javascript中,我有一个时间字符串var time = "12:30:49PM"
我想将小时,分钟,秒和AM / PM与该字符串分开。
浏览stackoverflow我能够找到以下正则表达式分割小时,分钟和上午/下午,但我在正则表达式上非常糟糕,所以我无法弄清楚如何做秒。
var hours = Number(time.match(/^(\d+)/)[1]);
var minutes = Number(time.match(/:(\d+)/)[1]);
var AMPM = time.match(/([AaPp][Mm])$/)[1];
如何通过正则表达式获得第二个
答案 0 :(得分:5)
您可以将正则表达式与ES6数组解构结合使用:
const time = "12:30:49PM"
const [hour, min, sec, period] = time.match(/\d+|\w+/g);
console.log(hour, min, sec, period);

答案 1 :(得分:5)
在您的示例中,您只需执行以下操作:
var time = "12:30:49PM";
var hours = Number(time.match(/^(\d+)/)[1]);
var minutes = Number(time.match(/:(\d+)/)[1]);
var AMPM = time.match(/([AaPp][Mm])$/)[1];
var seconds = Number(time.match(/:(\d+):(\d+)/)[2]);
console.log(hours, ":", minutes, ":", seconds, AMPM);

但是,在一次通话中获取所有内容会更有效:
var time = "12:30:49AM";
var matches = time.match(/^(\d+):(\d+):(\d+)([AP]M)$/i);
var hours = matches[1];
var minutes = matches[2];
var seconds = matches[3];
var AMPM = matches[4];
console.log(hours, ":", minutes, ":", seconds, AMPM);

答案 2 :(得分:1)
您可以像这样使用它:
var time = "12:30:49PM"
var hours = Number(time.match(/^(\d+)/)[1]);
var minutes = Number(time.match(/:(\d+)/)[1]);
var sec = Number(time.match(/:(\d+)\D+$/)[1]);
var AMPM = time.match(/([ap]m)$/i)[1];
console.log(hours);
console.log(minutes);
console.log(sec);
console.log(AMPM);
答案 3 :(得分:1)
分开冒号和(P \ A)M部分
var time = "12:30:49PM";
var parts = time.split(/:|(\DM)/).filter(Boolean);
console.log(parts)

答案 4 :(得分:0)
var sec = Number(time.match(/:([0-9][0-9])/ig)[1].replace(":",""))
答案 5 :(得分:0)
怎么样!
console.log(DateTimeFormat(new Date(), '`The Year is ${y} DateTime is: ${m}/${d}/${y} Time is: ${h}:${M}:${s} `'))
function DateTimeFormat(dt, fmt)
{
[y, m, d, h, M, s, ms] = new
Date(dt).toLocaleString('UTC').match(/\d+/g)
return eval(fmt)
}