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

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

    Here is a simple answer in basically one line of code.

    var value = 35 // the numerical value
    var x = 5 // the minimum length of the string
    
    var padded = ("00000" + value).substr(-x);
    

    Make sure the number of characters in you padding, zeros here, is at least as many as your intended minimum length. So really, to put it into one line, to get a result of "00035" in this case is:

    var padded = ("00000" + 35).substr(-5);
    

提交回复
热议问题