如何使用正则表达式在 Javascript 中 10 以下的任何数字前添加零

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8169785/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 02:31:22  来源:igfitidea点击:

How to prepend a zero in front of any number below 10 in Javascript using Regexp

javascriptregexdate

提问by Cybrix

Good day,

再会,

Is there a Regex that I could use to prepend a 0 before any number that is below 10?

是否有一个正则表达式可以用来在任何小于 10 的数字之前添加 0?

I am not looking for a date parsing library, ternary or if/else solutions. (hopefully)

我不是在寻找日期解析库、三元或 if/else 解决方案。(希望)

var currentDate = new Date(),
    stringDate = currentDate.getFullYear() + "-" + currentDate.getMonth() + "-" + currentDate.getDate() + " " + currentDate.getHours() + ":" + currentDate.getMinutes() + ":" + currentDate.getSeconds();

    alert( stringDate ); //2011-10-17 10:3:7

I would like a RegExp that I could apply to stringDate to get 2011-10-17 10:03:07

我想要一个可以应用于 stringDate 的 RegExp 以获得 2011-10-17 10:03:07

Thank you very much!

非常感谢你!

回答by Alex Peattie

Just add the leading 0 every time, then use slice(-2)to get the last two characters, like so:

每次只需添加前导 0,然后使用slice(-2)获取最后两个字符,如下所示:

('0' + currentDate.getHours()).slice(-2)

回答by Davan Etelamaki

The following function will allow you to declare a minimum length for a number along or within a string and will pad it with zeros to make it the appropriate length.

以下函数将允许您为字符串中或字符串中的数字声明最小长度,并用零填充它以使其成为适当的长度。

var PrependZeros = function (str, len, seperator) {
    if(typeof str === 'number' || Number(str)){
        str = str.toString();
        return (len - str.length > 0) ? new Array(len + 1 - str.length).join('0') + str: str;
    }
    else{
        for(var i = 0,spl = str.split(seperator || ' '); i < spl.length; spl[i] = (Number(spl[i])&& spl[i].length < len)?PrependZeros(spl[i],len):spl[i],str = (i == spl.length -1)?spl.join(seperator || ' '):str,i++);
        return str;
    }
};

For those wanting a less cryptic version

对于那些想要一个不那么神秘的版本的人

var PrependZeros = function (str, len, seperator) {
    if (typeof str === 'number' || Number(str)) {
        str = str.toString();
        return (len - str.length > 0) ? new Array(len + 1 - str.length).join('0') + str : str;
    }
    else {
        var spl = str.split(seperator || ' ')
        for (var i = 0 ; i < spl.length; i++) {
            if (Number(spl[i]) && spl[i].length < len) {
                spl[i] = PrependZeros(spl[i], len)
            }
        }
        return spl.join(seperator || ' ');
    }
};

Examples:

例子:

PrependZeros("1:2:3",2,":"); // "01:02:03"
PrependZeros(1,2); // "01"
PrependZeros(123,2); // "123"
PrependZeros("1 2 3",3); // "001 002 003" 
PrependZeros("5-10-2012",2,"-"); //"05-10-2012"

回答by Alex Turpin

You don't need regex for that. You can make a simple pad function yourself:

你不需要正则表达式。你可以自己做一个简单的pad函数:

function pad(n) {
    if (n < 10)
        return "0" + n;
    return n;
}

alert(pad(8));
alert(pad(11));

http://jsfiddle.net/DwnNG/

http://jsfiddle.net/DwnNG/

回答by Toto

How about:

怎么样:

x.replace(/^(\d)$/, "0");

回答by John

I now this is old, but I just saw this simple and clean solution used on the w3cand just had to share it somewhere.

我现在这已经过时了,但我刚刚在w3c上看到了这个简单而干净的解决方案,只好在某处分享它。

var hours = currentDate.getHours();
(hours < 10 ? '0' : '') + hours;

回答by Timo

%0{length} => %05 => 1=00001, 2=00002,... 55=00055,...

%0{长度} => %05 => 1=00001, 2=00002,... 55=00055,...

回答by Andreas

That should do the work (it has an ternary operator in it, but also an regex^^)

这应该可以完成工作(它有一个三元运算符,还有一个正则表达式^^)

stringDate.replace(/\d+/g, function(m) {
    return parseInt(m, 10) < 10 ? "0" + m : m;
});

回答by Ya Zhuang

I prefer Alex's way, but if you reallywant the regex way, you can try:

我更喜欢 Alex 的方式,但如果你真的想要正则表达式的方式,你可以尝试:

   "2011-10-10 10:2:27".replace(/:(?=[^0](?::|$))/g, ":0");

回答by John Strickler

Are you ready for your one-liner do-it-all regex solution?

您准备好使用单行全能正则表达式解决方案了吗?

Pass in your entire string... and this will match single-digits and pad them with a 0.

传入整个字符串……这将匹配单个数字并用 0 填充它们。

"2011-10-17 10:3:7"
.replace(/(^|[^0-9])([0-9])(?=($|[^0-9]))/ig, function (##代码##, ) { 
   return ##代码##[0] + '0' + ##代码##[1]; 
});

//returns "2011-10-17 10:03:07"

This would be made so much easier if JavaScript supported lookbehind-assertions.

如果 JavaScript 支持后视断言,这将变得更加容易。