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

JavascriptWeb DevelopmentObject Oriented Programming

We have to write a function, say padSting() 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 numbers at the end of the string so that its length becomes exactly equal to the number and we have to return the new string.

Therefore, let’s write the code for this function −

Example

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));

Output

The output in the console will be −

abc5189239
QWERTY2303
HELLO9332934005655101848049087
foo9039416
raja
Published on 21-Aug-2020 14:52:40
Advertisements