是否有可以填充字符串以达到确定长度的 JavaScript 函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2686855/
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
Is there a JavaScript function that can pad a string to get to a determined length?
提问by Anthony Potts
I am in need of a JavaScript function which can take a value and pad it to a given length (I need spaces, but anything would do). I found this:
我需要一个 JavaScript 函数,它可以接受一个值并将其填充到给定的长度(我需要空格,但什么都可以)。我找到了这个:
Code:
代码:
String.prototype.pad = function(l, s, t){
return s || (s = " "), (l -= this.length) > 0 ? (s = new Array(Math.ceil(l / s.length)
+ 1).join(s)).substr(0, t = !t ? l : t == 1 ? 0 : Math.ceil(l / 2))
+ this + s.substr(0, l - t) : this;
};
Example:
例子:
<script type="text/javascript">
//<![CDATA[
var s = "Jonas";
document.write(
'<h2>S = '.bold(), s, "</h2>",
'S.pad(20, "[]", 0) = '.bold(), s.pad(20, "[]", 0), "<br />",
'S.pad(20, "[====]", 1) = '.bold(), s.pad(20, "[====]", 1), "<br />",
'S.pad(20, "~", 2) = '.bold(), s.pad(20, "~", 2)
);
//]]>
</script>
But I have no idea what the heck it is doing and it doesn't seem to work for me.
但我不知道它到底在做什么,它似乎对我不起作用。
回答by Samuel
I found this solution hereand this is for me much much simpler:
我在这里找到了这个解决方案,这对我来说要简单得多:
var n = 123
String("00000" + n).slice(-5); // returns 00123
("00000" + n).slice(-5); // returns 00123
(" " + n).slice(-5); // returns " 123" (with two spaces)
And here I made an extension to the string object:
在这里,我对字符串对象进行了扩展:
String.prototype.paddingLeft = function (paddingValue) {
return String(paddingValue + this).slice(-paddingValue.length);
};
An example to use it:
一个使用它的例子:
function getFormattedTime(date) {
var hours = date.getHours();
var minutes = date.getMinutes();
hours = hours.toString().paddingLeft("00");
minutes = minutes.toString().paddingLeft("00");
return "{0}:{1}".format(hours, minutes);
};
String.prototype.format = function () {
var args = arguments;
return this.replace(/{(\d+)}/g, function (match, number) {
return typeof args[number] != 'undefined' ? args[number] : match;
});
};
This will return a time in the format "15:30"
这将返回格式为“15:30”的时间
回答by Shyam Habarakada
A faster method
更快的方法
If you are doing this repeatedly, for example to pad values in an array, and performance is a factor, the following approach can give you nearly a 100x advantagein speed (jsPerf) over other solution that are currently discussed on the inter webs. The basic idea is that you are providing the pad function with a fully padded empty string to use as a buffer. The pad function just appends to string to be added to this pre-padded string (one string concat) and then slices or trims the result to the desired length.
如果您重复执行此操作,例如填充数组中的值,并且性能是一个因素,那么与当前在互联网上讨论的其他解决方案相比,以下方法可以为您提供近100 倍的速度优势( jsPerf)。基本思想是为 pad 函数提供一个完全填充的空字符串以用作缓冲区。pad 函数只是附加到要添加到这个预先填充的字符串(一个字符串 concat)的字符串,然后将结果切片或修剪到所需的长度。
function pad(pad, str, padLeft) {
if (typeof str === 'undefined')
return pad;
if (padLeft) {
return (pad + str).slice(-pad.length);
} else {
return (str + pad).substring(0, pad.length);
}
}
For example, to zero pad a number to a length of 10 digits,
例如,要将一个数字零填充到 10 位数字的长度,
pad('0000000000',123,true);
To pad a string with whitespace, so the entire string is 255 characters,
用空格填充字符串,所以整个字符串是 255 个字符,
var padding = Array(256).join(' '), // make a string of 255 spaces
pad(padding,123,true);
Performance Test
性能测试
See the jsPerftest here.
请参阅此处的jsPerf测试。
And this is faster than ES6 string.repeatby 2x as well, as shown by the revised JsPerf here
这比ES6更快string.repeat的2倍为好,如通过修订后的JsPerf这里
回答by David
http://www.webtoolkit.info/javascript_pad.html
http://www.webtoolkit.info/javascript_pad.html
/**
*
* Javascript string pad
* http://www.webtoolkit.info/
*
**/
var STR_PAD_LEFT = 1;
var STR_PAD_RIGHT = 2;
var STR_PAD_BOTH = 3;
function pad(str, len, pad, dir) {
if (typeof(len) == "undefined") { var len = 0; }
if (typeof(pad) == "undefined") { var pad = ' '; }
if (typeof(dir) == "undefined") { var dir = STR_PAD_RIGHT; }
if (len + 1 >= str.length) {
switch (dir){
case STR_PAD_LEFT:
str = Array(len + 1 - str.length).join(pad) + str;
break;
case STR_PAD_BOTH:
var padlen = len - str.length;
var right = Math.ceil( padlen / 2 );
var left = padlen - right;
str = Array(left+1).join(pad) + str + Array(right+1).join(pad);
break;
default:
str = str + Array(len + 1 - str.length).join(pad);
break;
} // switch
}
return str;
}
It's a lot more readable.
它更具可读性。
回答by hypno7oad
Here's a recursive approach to it.
这是一个递归的方法。
function pad(width, string, padding) {
return (width <= string.length) ? string : pad(width, padding + string, padding)
}
An example...
一个例子...
pad(5, 'hi', '0')
=> "000hi"
回答by ChrisV
String.prototype.padStart()and String.prototype.padEnd()are currently TC39 candidate proposals: see github.com/tc39/proposal-string-pad-start-end(only available in Firefox as of April 2016; a polyfillis available).
String.prototype.padStart()而String.prototype.padEnd()目前TC39候选人的提案:见github.com/tc39/proposal-string-pad-start-end(仅在Firefox可作为2016年4月的;一个填充工具可用)。
回答by arMedBeta
ECMAScript 2017 adds a padStart method to the String prototype. This method will pad a string with spaces to a given length. This method also takes an optional string that will be used instead of spaces for padding.
ECMAScript 2017 向 String 原型添加了 padStart 方法。此方法将用空格填充字符串到给定的长度。此方法还采用一个可选的字符串,用于代替空格进行填充。
'abc'.padStart(10); // " abc"
'abc'.padStart(10, "foo"); // "foofoofabc"
'abc'.padStart(6,"123465"); // "123abc"
'abc'.padStart(8, "0"); // "00000abc"
'abc'.padStart(1); // "abc"
A padEnd method was also added that works in the same manner.
还添加了以相同方式工作的 padEnd 方法。
For browser compatibility (and a useful polyfill) see this link.
有关浏览器兼容性(和有用的 polyfill),请参阅此链接。
回答by Guss
Using the ECMAScript 6 method String#repeat, a pad function is as simple as:
使用 ECMAScript 6 方法String#repeat,pad 函数非常简单:
String.prototype.padLeft = function(char, length) {
return char.repeat(Math.max(0, length - this.length)) + this;
}
String#repeatis currently supported in Firefox and Chrome only. for other implementation, one might consider the following simple polyfill:
String#repeat目前仅 Firefox 和 Chrome 支持。对于其他实现,可以考虑以下简单的 polyfill:
String.prototype.repeat = String.prototype.repeat || function(n){
return n<=1 ? this : (this + this.repeat(n-1));
}
回答by Pointy
The key trick in both those solutions is to create an arrayinstance with a given size (one more than the desired length), and then to immediately call the join()method to make a string. The join()method is passed the padding string(spaces probably). Since the arrayis empty, the empty cells will be rendered as empty stringsduring the process of joining the arrayinto one result string, and only the padding will remain. It's a really nice technique.
这两种解决方案的关键技巧是创建一个array具有给定大小(比所需长度多一个)的实例,然后立即调用该join()方法来创建一个string. 该join()方法通过填充string(可能是空格)。由于 thearray为空,因此strings在将 thearray合并为一个 result的过程中,空单元格将呈现为空string,并且仅保留填充。这是一个非常好的技术。
回答by InsOp
Using the ECMAScript 6 method String#repeatand Arrow functions, a pad function is as simple as:
使用 ECMAScript 6 方法String#repeat和Arrow 函数,pad 函数非常简单:
var leftPad = (s, c, n) => c.repeat(n - s.length) + s;
leftPad("foo", "0", 5); //returns "00foo"
edit:suggestion from the comments:
编辑:来自评论的建议:
const leftPad = (s, c, n) => n - s.length > 0 ? c.repeat(n - s.length) + s : s;
this way, it wont throw an error when s.lengthis greater than n
这样,当s.length大于时它不会抛出错误n
edit2:suggestion from the comments:
编辑2:来自评论的建议:
const leftPad = (s, c, n) =>{ s = s.toString(); c = c.toString(); return s.length > n ? s : c.repeat(n - s.length) + s; }
this way, you can use the function for strings and non-strings alike.
这样,您可以将该函数用于字符串和非字符串。
回答by Sornii
With ES8, there are two options for padding.
在 ES8 中,有两种填充选项。
You can check them in the documentation.
您可以在文档中查看它们。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padEnd
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padEnd
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

