Javascript Javascript在字符串的开头添加零(最大长度为4个字符)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4726040/
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
Javascript adding zeros to the beginning of a string (max length 4 chars)
提问by Kyle Wild
var number = 1310;
should be left alone.
应该单独留下。
var number = 120;
should be changed to "0120";
应改为“0120”;
var number = 10;
should be changed to "0010";
应改为“0010”;
var number = 7;
should be changed to "0007";
应改为“0007”;
回答by Kyle Wild
function pad_with_zeroes(number, length) {
var my_string = '' + number;
while (my_string.length < length) {
my_string = '0' + my_string;
}
return my_string;
}
回答by Lifehack
In all modern browsers you can use
在所有现代浏览器中,您都可以使用
numberStr.padStart(4, "0");
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart
function zeroPad(num) {
return num.toString().padStart(4, "0");
}
var numbers = [1310, 120, 10, 7];
numbers.forEach(
function(num) {
var paddedNum = zeroPad(num);
console.log(paddedNum);
}
);
回答by Nate
Here's another way. Comes from something I did that needs to be done thousands of times on a page load. It's pretty CPU efficient to hard code a string of zeroes one time, and chop as many as you need for the pad as many times as needed. I do really like the power of 10 method -- that's pretty flexible.
这是另一种方式。来自我所做的需要在页面加载时完成数千次的事情。一次对一串零进行硬编码,并根据需要根据需要多次切碎打击垫,这是非常有效的 CPU 效率。我真的很喜欢 10 方法的威力——它非常灵活。
Anyway, this is as efficient as I could come up with:
无论如何,这和我能想到的一样有效:
For the original question,CHOOSE ONE of the cases...
对于原始问题,请选择其中一种情况...
var number = 1310;
var number = 120;
var number = 10;
var number = 7;
then
然后
// only needs to happen once
var zeroString = "00000";
// one assignment gets the padded number
var paddedNum = zeroString.substring((number + "").length, 4) + bareNum;
//output
alert("The padded number string is: " + paddedNum);
Of course you still need to validate the input. Because this ONLY works reliably under the following conditions:
当然,您仍然需要验证输入。因为这仅在以下条件下可靠地工作:
- Number of zeroes in the zeroString is desired_length + 1
- Number of digits in your starting number is less than or equal to your desired length
- zeroString 中的零数为 desired_length + 1
- 您的起始号码中的位数小于或等于您想要的长度
Backstory:
背景故事:
I have a case that needs a fixed length (14 digit) zero-padded number. I wanted to see how basic I could make this. It's run tens of thousands of times on a page load, so efficiency matters. It's not quite re-usable as-is, and it's a bit inelegant. Except that it is very very simple.
我有一个需要固定长度(14 位)零填充数字的案例。我想看看我能做到多么基本。它在页面加载时运行数万次,因此效率很重要。它不能按原样重复使用,而且有点不雅。除了它非常非常简单。
For desired n digits padded string, this method requires a string of (at least) n+1 zeroes. Index 0 is the first character in the string, which won't ever be used, so really, it could be anything.
对于所需的 n 位填充字符串,此方法需要(至少)n+1 个零的字符串。索引 0 是字符串中的第一个字符,永远不会被使用,所以实际上,它可以是任何东西。
Note also that string.substring()is different from string.substr()!
还要注意string.substring()与string.substr()不同!
var bareNum = 42 + '';
var zeroString = "000000000000000";
var paddedNum = zeroString.substring(bareNumber.length, 14) + bareNum
This pulls zeroes from zeroString starting at the position matching the length of the string, and continues to get zeroes to the necessary length of 14. As long as that "14" in the third line is a lower integer than the number of characters in zeroString, it will work.
这从与字符串长度匹配的位置开始从 zeroString 拉零,并继续获取零到必要的长度 14。只要第三行中的“14”是一个小于 zeroString 中字符数的整数,它会起作用。
回答by mzfr
try these:
试试这些:
('0000' + number).slice(-4);
or
或者
(number+'').padStart(4,'0');
回答by Mykytak
//to: 0 - to left, 1 - to right
String.prototype.pad = function(_char, len, to) {
if (!this || !_char || this.length >= len) {
return this;
}
to = to || 0;
var ret = this;
var max = (len - this.length)/_char.length + 1;
while (--max) {
ret = (to) ? ret + _char : _char + ret;
}
return ret;
};
Usage:
用法:
someString.pad(neededChars, neededLength)
Example:
例子:
'332'.pad('0', 6); //'000332'
'332'.pad('0', 6, 1); //'332000'
回答by Pointy
function pad(n, len) {
return (new Array(len + 1).join('0') + n).slice(-len);
}
might not work in old IE versions.
可能不适用于旧的 IE 版本。
回答by kojiro
An approach I like is to add 10^N to the number, where N is the number of zeros you want. Treat the resultant number as a string and slice off the zeroth digit. Of course, you'll want to be careful if your input number might be larger than your pad length, but it's still much faster than the loop method:
我喜欢的一种方法是将 10^N 添加到数字中,其中 N 是您想要的零的数量。将结果数字视为字符串并切掉第零个数字。当然,如果您的输入数字可能大于您的填充长度,您需要小心,但它仍然比循环方法快得多:
// You want to pad four places:
>>> var N = Math.pow(10, 4)
>>> var number = 1310
>>> number < N ? ("" + (N + number)).slice(1) : "" + number
"1310"
>>> var number = 120
>>> number < N ? ("" + (N + number)).slice(1) : "" + number
"0120"
>>> var number = 10
>>> number < N ? ("" + (N + number)).slice(1) : "" + number
"0010"
…
etc. You can make this into a function easily enough:
等等。你可以很容易地把它变成一个函数:
/**
* Pad a number with leading zeros to "pad" places:
*
* @param number: The number to pad
* @param pad: The maximum number of leading zeros
*/
function padNumber(number, pad) {
var N = Math.pow(10, pad);
return number < N ? ("" + (N + number)).slice(1) : "" + number
}
回答by gillall
No loop, no functions
没有循环,没有功能
let n = "" + 100;
let x = ("0000000000" + n).substring(n.length);//add your amount of zeros
alert(x + "-" + x.length);
回答by Kristian Benoit
Nate as the best way I found, it's just way too long to read. So I provide you with 3 simples solutions.
Nate 是我找到的最好的方式,只是阅读时间太长了。因此,我为您提供了 3 个简单的解决方案。
1. So here's my simplification of Nate's answer.
1. 这是我对 Nate 答案的简化。
//number = 42
"0000".substring(number.toString().length, 4) + number;
2. Here's a solution that make it more reusable by using a function that takes the number and the desired length in parameters.
2. 这是一个解决方案,它通过使用一个函数来提高它的可重用性,该函数将数字和所需的长度作为参数。
function pad_with_zeroes(number, len) {
var zeroes = "0".repeat(len);
return zeroes.substring(number.toString().length, len) + number;
}
// Usage: pad_with_zeroes(42,4);
// Returns "0042"
3. Here's a third solution, extending the Number prototype.
3. 这是第三种解决方案,扩展 Number 原型。
Number.prototype.toStringMinLen = function(len) {
var zeroes = "0".repeat(len);
return zeroes.substring(self.toString().length, len) + self;
}
//Usage: tmp=42; tmp.toStringMinLen(4)
回答by Masoud Keshavarz
I wrote a general function for this. It takes an input control and pad length as input.
我为此编写了一个通用函数。它需要一个输入控件和填充长度作为输入。
function padLeft(input, padLength) {
var num = $("#" + input).val();
$("#" + input).val(('0'.repeat(padLength) + num).slice(-padLength));
}