I receive an integer, for example 3, and I want to display a string such as "0000003" (six "0's" and "3"). Or receive the 1050 and display "0001050" (three "0" and the number).
Therefore, what I want is to show a 7-digit integer to which to add a number, showing the remaining 0.
var numero = 3;
var cadenaNumerica = 0000000;
var resultado = numero + cadenaNumerica;
//Lo que necesito que devuelva resultado 0000003
ECMA Script 2017 includes -finally- a function to do it:
padStart()
The syntax is:
Where:
tamaño
is the size of the resulting string.cadena_con_la_que_hacer_padding
is " " (a space) by default.So you would do something like:
Javascript doesn't have a function to do the job (like a
sprintf
C one).What you need instead is to add the zeros at the beginning (as a string) and add the number at the end to it. Finally you keep only the right part of the result (in the event that they are integers).
Here's an example:
Thanks to @fedorqui's answer I know the ECMA Script 2017 proposal for
String.prototype.padStart
.The problem is that currently it is only supported by the latest versions of some browsers, so it occurs to me that you could check the existence of the implementation and if it is not available create a "light" version that emulates its basic behavior:
PS: I don't use the reference implementation because it relies on
String.prototype.repeat
it not being supported in all browsers either.Numbers are padded to the right using a logarithm and with regular expressions, they move immediately to the left and the point is removed.
First fill in the remaining zeros to the right, which is the number of digits subtracted from the base 10 logarithm of the number.
Then with the regular expression it is separated into two parts, the number and the amount of zeros on the right, and the order is changed.
Another simpler way is to add to the number, 10 raised to the number of digits, then transform it into a string and remove the first character.
Example: