Remove leading zeros from time format

2020-03-03 04:01发布

I am receiving a string in this format 'HH:mm:ss'. I would like to remove the leading zeros but always keeping the the last four character eg m:ss even if m would be a zero. I am formatting audio duration.

Examples:

00:03:15 => 3:15
10:10:10 => 10:10:10
00:00:00 => 0:00
04:00:00 => 4:00:00
00:42:32 => 42:32
00:00:18 => 0:18
00:00:08 => 0:08

4条回答
Melony?
2楼-- · 2020-03-03 04:14

You can use this replacement:

var result = yourstr.replace(/^(?:00:)?0?/, '');

demo

or better:

var result = yourstr.replace(/^0(?:0:0?)?/, '');

demo

查看更多
家丑人穷心不美
3楼-- · 2020-03-03 04:21

You could do something like this:

var tc =['00:03:15', '10:10:10','00:00:00','04:00:00','00:42:32','00:00:18','00:00:08'];

tc.forEach(function(t) {
    var y = t.split(":");
    y[0] = y[0].replace(/^[0]+/g, '');
    if(y[0] === '') {
        y[1] = y[1].replace(/^0/g, ''); 
    }
    var r = y.filter(function(p) {return p!=='';}).join(':');
    console.log(r);
});

Divide the time in 3 parts. Remove the leading zeroes from first part, if the the first part is empty remove the leading zeroes from the second part otherwise keep it. Then join all of them discarding the empty strings.

查看更多
干净又极端
4楼-- · 2020-03-03 04:28

Another option is to use moment.js libary.

This supports formats such as

var now = moment('1-1-1981 2:44:22').format('h:mm:ss');
alert(now);

http://jsfiddle.net/8yqxh5mo/

查看更多
来,给爷笑一个
5楼-- · 2020-03-03 04:36

If you use 1 h instead of two you will not get the leading 0.

h:mm:ss

查看更多
登录 后发表回答