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

前端 未结 30 1786
悲哀的现实
悲哀的现实 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条回答
  •  暖寄归人
    2020-11-22 09:05

    1. Never insert data somewhere (especially not at beginning, like str = pad + str;), since the data will be reallocated everytime. Append always at end!
    2. Don't pad your string in the loop. Leave it alone and build your pad string first. In the end concatenate it with your main string.
    3. Don't assign padding string each time (like str += pad;). It is much faster to append the padding string to itself and extract first x-chars (the parser can do this efficiently if you extract from first char). This is exponential growth, which means that it wastes some memory temporarily (you should not do this with extremely huge texts).

    if (!String.prototype.lpad) {
        String.prototype.lpad = function(pad, len) {
            while (pad.length < len) {
                pad += pad;
            }
            return pad.substr(0, len-this.length) + this;
        }
    }
    
    if (!String.prototype.rpad) {
        String.prototype.rpad = function(pad, len) {
            while (pad.length < len) {
                pad += pad;
            }
            return this + pad.substr(0, len-this.length);
        }
    }

提交回复
热议问题