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

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

    If you just want a very simple hacky one-liner to pad, just make a string of the desired padding character of the desired max padding length and then substring it to the length of what you want to pad.

    Example: padding the string store in e with spaces to 25 characters long.

    var e = "hello"; e = e + "                         ".substring(e.length)
    

    Result: "hello "

    If you want to do the same with a number as input just call .toString() on it before.

提交回复
热议问题