Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,851 questions

51,772 answers

573 users

How to add leading zeros to the shorter string of two strings in Node.js

1 Answer

0 votes
function addLeadingZero(str1, str2) {
    const len1 = str1.length;
    const len2 = str2.length;
 
    let strToPad = "";
 
    const diff = Math.abs(len1 - len2);
 
    if (diff > 0) {
        strToPad = "0".repeat(diff);
        if (len1 > len2) {
            strToPad += str2;
        } else {
            strToPad += str1;
        }
    }
 
    return strToPad;
}
 
let str1 = "789";
let str2 = "1298653";
 
if (str1.length > str2.length) {
    str2 = addLeadingZero(str1, str2);
} else {
    str1 = addLeadingZero(str1, str2);
}
 
console.log(str1);
console.log(str2);
 
 
 
 
/*
run:
 
0000789
1298653
 
*/

 



answered May 28, 2024 by avibootz

Related questions

...