Padding a string with random lowercase alphabets to fill length in JavaScript

We are required to write a function that takes in two arguments, first is a string and second is a number. The length of string is always less than or equal to the number. We have to insert some random lowercase alphabets at the end of the string so that its length becomes exactly equal to the number and we have to return the new string.

Example

Let's write the code for this function ?

const padString = (str, len) => {
    if(str.length < len){
        const random = Math.floor(Math.random() * 26);
        const randomAlpha = String.fromCharCode(97 + random);
        return padString(str + randomAlpha, len);
    };
    return str;
};
console.log(padString('abc', 10));
console.log(padString('QWERTY', 10));
console.log(padString('HELLO', 30));
console.log(padString('foo', 10));

Output

The output in the console ?

abckoniucl
QWERTYcwaf
HELLOdnulywbogqhypgmylqlvmckhg
foofhfnhon

How It Works

The function uses recursion to add random lowercase letters one by one:

  • Math.random() * 26 generates a number between 0-25
  • String.fromCharCode(97 + random) converts to lowercase letter (97 is ASCII code for 'a')
  • The function calls itself recursively until the string reaches the desired length

Alternative Approach Using Loop

Here's a non-recursive version using a while loop:

const padStringLoop = (str, len) => {
    let result = str;
    while(result.length < len) {
        const random = Math.floor(Math.random() * 26);
        const randomAlpha = String.fromCharCode(97 + random);
        result += randomAlpha;
    }
    return result;
};

console.log(padStringLoop('test', 8));
console.log(padStringLoop('JS', 6));
testabcd
JSefgh

Conclusion

Both recursive and iterative approaches work effectively for padding strings with random lowercase letters. The recursive version is more elegant, while the loop version may be more intuitive for some developers.

Updated on: 2026-03-15T23:19:00+05:30

305 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements