let m = 5;
m = m.padStart(2, '0');
Error:
m.padStart is not a function
Expecting result: 05
;
I'm on Chrome, last version.
Any help?
padStart() The padStart() method pads the current string with another string (multiple times, if needed) until the resulting string reaches the given length. The padding is applied from the start of the current string.
Calling . padStart(length) or . padEnd(length) returns a new string of the given length, with the start or end of the string padded with spaces. These padding functions do not modify the string that they are called on.
The padStart() method pads the current string with another string (multiple times, if needed) until the resulting string reaches the given length. The padding is applied from the start (left) of the current string.
It is a String function. Not a number function. Refer
Solution-
let m = '5';
m = m.padStart(2, '0');
alert(m)
Convert your value from int
to String
just like this int.toString().padStart(n, '0');
change the number value to string , I was need this function to convert current hour value to leading zero number , your example should be
let m = 5+''; // just in case you can't change the actual number variable .
m = m.padStart(2, '0');
my code that i was need it
function CurrentTime( ) {
var today = new Date();
var h = today.getHours( )+'' ; var m = today.getMinutes()+'' ;
return h.padStart( 2 , '0' ) +':'+m.padStart( 2 , '0' ) ;
}
var current = CurrentTime( ) ;
var timeNow = mydiv.innerText ; console.log("current: " + current) ;
Since padStart()
is not compatible with Internet Explorer (IE) and other old browser versions and if you try using it with numbers you can get:
let m = 5;
m = m.padStart(2, '0');
alert(m);
Uncaught TypeError: m.padStart is not a function at :2:7
Here I am to provide you a function that I created, it works fine with Strings as well as Numbers in case that somebody need something like that padding a Number to 01, 02, .. 09:
let m = 5;
m = padValue(m);
alert(m);
// Sam pading value to start with 0. eg: 01, 02, .. 09, 10, ..
function padValue(value) {
return (value < 10) ? "0" + value : value;
}
As I mentioned you can replace assigned 5 value to 05:
let m = '5'; // The result will be 05
If you pass a value greater than 9 as String or Number will display the value without adding the padding. e.g.:
let m = '10'; // The result will be 10
Or
let m = 10; // The result will be 10
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With