Is there a JavaScript function that can pad a string to get to a determined length?

前端 未结 30 1672
悲哀的现实
悲哀的现实 2020-11-22 08:28

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:

30条回答
  •  Happy的楠姐
    2020-11-22 09:15

    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

提交回复
热议问题