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

前端 未结 30 1852
悲哀的现实
悲哀的现实 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 08:58

    Array manipulations are really slow compared to simple string concat. Of course, benchmark for your use case.

    function(string, length, pad_char, append) {
        string = string.toString();
        length = parseInt(length) || 1;
        pad_char = pad_char || ' ';
    
        while (string.length < length) {
            string = append ? string+pad_char : pad_char+string;
        }
        return string;
    };
    

提交回复
热议问题