Is there a JavaScript function that can pad a stri

2018-12-31 13:14发布

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:

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.

30条回答
人间绝色
2楼-- · 2018-12-31 13:48

The key trick in both those solutions is to create an array instance 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 array is empty, the empty cells will be rendered as empty strings during the process of joining the array into one result string, and only the padding will remain. It's a really nice technique.

查看更多
深知你不懂我心
3楼-- · 2018-12-31 13:51

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

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

pad('0000000000',123,true);

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

Performance Test

See the jsPerf test here.

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

查看更多
君临天下
4楼-- · 2018-12-31 13:51

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.

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

For browser compatibility (and a useful polyfill) see this link.

查看更多
余生无你
5楼-- · 2018-12-31 13:51

padding string has been inplemented in new javascript version.

str.padStart(targetLength [, padString])

https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/String/padStart

If you want your own function check this example:

const myString = 'Welcome to my house';
String.prototype.padLeft = function(times = 0, str = ' ') {
    return (Array(times).join(str) + this);
}
console.log(myString.padLeft(12, ':'));
//:::::::::::Welcome to my house
查看更多
素衣白纱
6楼-- · 2018-12-31 13:51

A variant of @Daniel LaFavers' answer.

var mask = function (background, foreground) {
  bg = (new String(background));
  fg = (new String(foreground));
  bgl = bg.length;
  fgl = fg.length;
  bgs = bg.substring(0, Math.max(0, bgl - fgl));
  fgs = fg.substring(Math.max(0, fgl - bgl));
  return bgs + fgs;
};

For example:

mask('00000', 11  );   // '00011'
mask('00011','00' );   // '00000'
mask( 2     , 3   );   // '3'
mask('0'    ,'111');   // '1'
mask('fork' ,'***');   // 'f***'
mask('_____','dog');   // '__dog'
查看更多
临风纵饮
7楼-- · 2018-12-31 13:51

If you don't mind including a utility library, lodash library has _.pad, _.padLeft and _.padRight functions.

查看更多
登录 后发表回答