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

查看:23
本文介绍了是否有可以填充字符串以达到确定长度的 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, but I have no idea what the heck it is doing and it doesn't seem to work for me.

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



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

推荐答案

更快的方法

如果您重复执行此操作,例如填充数组中的值,并且性能是一个因素,则以下方法可以为您提供近 100 倍的速度优势(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

请注意,我们最初用于对各种方法进行基准测试的 jsPerf 站点已不再在线.不幸的是,这意味着我们无法获得这些测试结果.悲伤但真实.

Please note that the jsPerf site that we originally used to benchmark the various methods is no longer online. Unfortunately, this means we can't get to those test results. Sad but true.

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

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