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

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

    Using the ECMAScript 6 method String#repeat and Arrow functions, a pad function is as simple as:

    var leftPad = (s, c, n) => c.repeat(n - s.length) + s;
    leftPad("foo", "0", 5); //returns "00foo"
    

    jsfiddle

    edit: suggestion from the comments:

    const leftPad = (s, c, n) => n - s.length > 0 ? c.repeat(n - s.length) + s : s;
    

    this way, it wont throw an error when s.lengthis greater than n

    edit2: suggestion from the comments:

    const leftPad = (s, c, n) =>{ s = s.toString(); c = c.toString(); return s.length > n ? s : c.repeat(n - s.length) + s; }
    

    this way, you can use the function for strings and non-strings alike.

提交回复
热议问题