How to add N zeros to an empty string in JavaScript

2 Answers

0 votes
function padLeft(str, length, char) {
    return char.repeat(Math.max(0, length - str.length)) + str;
}

const n = 4;
let emptyString = "";

emptyString = padLeft(emptyString, n, '0');

console.log(emptyString);




/*
run:

0000

*/

 



answered May 28, 2024 by avibootz
0 votes
function padLeftZeros(str, length) {
    return "0".repeat(length);
}
 
const n = 4;
let emptyString = "";
 
emptyString = padLeftZeros(emptyString, n);
 
console.log(emptyString);
 
 
 
 
/*
run:
 
0000
 
*/

 



answered May 28, 2024 by avibootz

Related questions

1 answer 126 views
1 answer 134 views
2 answers 143 views
1 answer 126 views
126 views asked May 26, 2024 by avibootz
1 answer 146 views
2 answers 129 views
129 views asked May 26, 2024 by avibootz
2 answers 165 views
...