[英]How to prepend a zero in front of any number below 10 in Javascript using Regexp
美好的一天,
有沒有一個正則表達式,我可以用來在任何低於10的數字前加0?
我不是在尋找日期解析庫,三元或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
我想要一個可以應用於stringDate的RegExp來獲得2011-10-17 10:03:07
非常感謝你!
只需每次添加前導0,然后使用slice(-2)
來獲取最后兩個字符,如下所示:
('0' + currentDate.getHours()).slice(-2)
以下函數將允許您在字符串中或字符串內聲明數字的最小長度,並使用零填充它以使其成為適當的長度。
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;
}
};
對於那些想要一個不那么神秘版本的人
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 || ' ');
}
};
例子:
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"
你不需要正則表達式。 你可以自己制作一個簡單的墊功能:
function pad(n) {
if (n < 10)
return "0" + n;
return n;
}
alert(pad(8));
alert(pad(11));
我現在已經老了,但我剛看到w3c上使用的這個簡單而干凈的解決方案,只是不得不在某處分享它。
var hours = currentDate.getHours();
(hours < 10 ? '0' : '') + hours;
怎么樣:
x.replace(/^(\d)$/, "0$1");
%0 {length} =>%05 => 1 = 00001,2 = 00002,... 55 = 00055,...
那應該做的工作(它有一個三元運算符,但也是一個正則表達式^^)
stringDate.replace(/\d+/g, function(m) {
return parseInt(m, 10) < 10 ? "0" + m : m;
});
我更喜歡Alex的方式,但如果你真的想要正則表達式,你可以嘗試:
"2011-10-10 10:2:27".replace(/:(?=[^0](?::|$))/g, ":0");
你准備好了單行全能正則表達式解決方案嗎?
傳入你的整個字符串...這將匹配單位數字並用0填充它們。
"2011-10-17 10:3:7"
.replace(/(^|[^0-9])([0-9])(?=($|[^0-9]))/ig, function ($0, $1) {
return $0[0] + '0' + $0[1];
});
//returns "2011-10-17 10:03:07"
如果JavaScript支持lookbehind-assertions,這將變得更加容易。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.