Pad a string using random numbers to a fixed length using JavaScript

We need to write a function that takes a string and a target length, then pads the string with random numbers until it reaches the specified length. This is useful for creating fixed-length identifiers or codes.

How It Works

The function uses recursion to add random digits (0-9) to the end of the string until it reaches the target length. Each recursive call generates a new random digit using Math.random().

Implementation

const padString = (str, len) => {
    if(str.length < len){
        const random = Math.floor(Math.random() * 10);
        return padString(str + random, len);
    };
    return str;
};

console.log(padString('abc', 10));
console.log(padString('QWERTY', 10));
console.log(padString('HELLO', 30));
console.log(padString('foo', 10));
abc5189239
QWERTY2303
HELLO9332934005655101848049087
foo9039416

Alternative Implementation Using While Loop

Here's a non-recursive approach that achieves the same result:

const padStringIterative = (str, len) => {
    let result = str;
    while(result.length < len) {
        const random = Math.floor(Math.random() * 10);
        result += random;
    }
    return result;
};

console.log(padStringIterative('test', 12));
console.log(padStringIterative('JS', 8));
test73629481
JS940517

Key Points

  • Math.floor(Math.random() * 10) generates random digits from 0-9
  • The function handles cases where the string is already at or above the target length
  • Each call produces different results due to randomness
  • Both recursive and iterative approaches work effectively

Common Use Cases

  • Creating unique identifiers with fixed lengths
  • Generating test data for databases
  • Padding serial numbers or product codes
  • Creating randomized tokens for temporary use

Conclusion

This padding function provides a simple way to extend strings to fixed lengths using random digits. The recursive approach is elegant, while the iterative version may be more familiar to some developers.

Updated on: 2026-03-15T23:18:59+05:30

437 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements