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

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

    Here's a recursive approach to it.

    function pad(width, string, padding) { 
      return (width <= string.length) ? string : pad(width, padding + string, padding)
    }
    

    An example...

    pad(5, 'hi', '0')
    => "000hi"
    

提交回复
热议问题