是否有一个JavaScript函数可以填充字符串以达到确定的长度? [英] Is there a JavaScript function that can pad a string to get to a determined length?

查看:104
本文介绍了是否有一个JavaScript函数可以填充字符串以达到确定的长度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个JavaScript函数,它可以获取一个值并将其填充到给定的长度(我需要空格,但任何事情都可以)。我发现了这个:

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:

代码:

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;
};

示例:

<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.

推荐答案

更快的方法



如果您反复这样做,例如填充数组中的值,性能是一个因素,以下方法可以为您提供近乎 100x优势的速度( jsPerf )目前在互联网上讨论的其他解决方案。基本思想是为pad函数提供一个完全填充的空字符串,用作缓冲区。 pad函数只是附加到要添加到此预填充字符串的字符串(一个字符串concat),然后将结果切片或修剪为所需长度。

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 advantage in 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.

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);
  }
}

例如,将数字填零为一个长度10位数,

For example, to zero pad a number to a length of 10 digits,

pad('0000000000',123,true);

用空格填充字符串,所以整个字符串为255个字符,

To pad a string with whitespace, so the entire string is 255 characters,

var padding = Array(256).join(' '), // make a string of 255 spaces
pad(padding,123,true);



性能测试



参见 jsPerf 测试此处

这是比ES6 string.repeat 快2倍,如修订后的JsPerf 这里

And this is faster than ES6 string.repeat by 2x as well, as shown by the revised JsPerf here

这篇关于是否有一个JavaScript函数可以填充字符串以达到确定的长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆