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

前端 未结 30 1336
悲哀的现实
悲哀的现实 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

    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
    

提交回复
热议问题