在 JavaScript 中将“1”转换为“0001”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5366849/
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
convert '1' to '0001' in JavaScript
提问by Maggie
Possible Duplicate:
Is there a JavaScript function that can pad a string to get to a determined length?
How can I convert convert '1' to '0001' in JavaScript without using any 3rd party libraries. I have done this in php using spritf: $time = sprintf('%04.0f',$time_arr[$i]);
如何在不使用任何 3rd 方库的情况下在 JavaScript 中将“1”转换为“0001”。我已经使用 spritf 在 php 中完成了此操作:$time = sprintf('%04.0f',$time_arr[$i]);
回答by
This is a clever little trick (that I think I've seen on SO before):
这是一个聪明的小技巧(我想我以前在 SO 上见过):
var str = "" + 1
var pad = "0000"
var ans = pad.substring(0, pad.length - str.length) + str
JavaScript is more forgiving than some languages if the second argument to substring is negative so it will "overflow correctly" (or incorrectly depending on how it's viewed):
如果 substring 的第二个参数是负数,JavaScript 比某些语言更宽容,因此它将“正确溢出”(或错误地取决于它的查看方式):
That is, with the above:
也就是说,与上述:
- 1 -> "0001"
- 12345 -> "12345"
- 1 -> “0001”
- 12345 -> “12345”
Supporting negative numbers is left as an exercise ;-)
支持负数作为练习;-)
Happy coding.
快乐编码。
回答by KooiInc
Just to demonstrate the flexibility of javascript: you can use a oneliner for this
只是为了展示 javascript 的灵活性:您可以为此使用 oneliner
function padLeft(nr, n, str){
return Array(n-String(nr).length+1).join(str||'0')+nr;
}
//or as a Number prototype method:
Number.prototype.padLeft = function (n,str){
return Array(n-String(this).length+1).join(str||'0')+this;
}
//examples
console.log(padLeft(23,5)); //=> '00023'
console.log((23).padLeft(5)); //=> '00023'
console.log((23).padLeft(5,' ')); //=> ' 23'
console.log(padLeft(23,5,'>>')); //=> '>>>>>>23'
If you want to use this for negative numbers also:
如果您还想将其用于负数:
Number.prototype.padLeft = function (n,str) {
return (this < 0 ? '-' : '') +
Array(n-String(Math.abs(this)).length+1)
.join(str||'0') +
(Math.abs(this));
}
console.log((-23).padLeft(5)); //=> '-00023'
Alternative if you don't want to use Array
:
如果您不想使用替代方法Array
:
number.prototype.padLeft = function (len,chr) {
var self = Math.abs(this)+'';
return (this<0 && '-' || '')+
(String(Math.pow( 10, (len || 2)-self.length))
.slice(1).replace(/0/g,chr||'0') + self);
}
回答by kennebec
String.prototype.padZero= function(len, c){
var s= this, c= c || '0';
while(s.length< len) s= c+ s;
return s;
}
dispite the name, you can left-pad with any character, including a space. I never had a use for right side padding, but that would be easy enough.
尽管名称不同,但您可以使用任何字符(包括空格)向左填充。我从来没有使用过右侧填充,但这很容易。
回答by Marcello Nuccio
I use the following object:
我使用以下对象:
function Padder(len, pad) {
if (len === undefined) {
len = 1;
} else if (pad === undefined) {
pad = '0';
}
var pads = '';
while (pads.length < len) {
pads += pad;
}
this.pad = function (what) {
var s = what.toString();
return pads.substring(0, pads.length - s.length) + s;
};
}
With it you can easily define different "paddings":
有了它,您可以轻松定义不同的“填充”:
var zero4 = new Padder(4);
zero4.pad(12); // "0012"
zero4.pad(12345); // "12345"
zero4.pad("xx"); // "00xx"
var x3 = new Padder(3, "x");
x3.pad(12); // "x12"