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

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

    Taking up Samuel's ideas, upward here. And remember an old SQL script, I tried with this:

    a=1234;
    '0000'.slice(a.toString().length)+a;
    

    It works in all the cases I could imagine:

    a=     1 result  0001
    a=    12 result  0012
    a=   123 result  0123
    a=  1234 result  1234
    a= 12345 result 12345
    a=  '12' result  0012
    

提交回复
热议问题