- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Pad a string using random numbers to a fixed length using JavaScript
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
- Related Articles
- Generating random string with a specific length in JavaScript
- Padding a string with random lowercase alphabets to fill length in JavaScript
- How to decrease size of a string by using preceding numbers - JavaScript?
- Generating random string of specified length in JavaScript
- Generate random numbers using C++11 random library
- Summing array of string numbers using JavaScript
- Summing numbers present in a string separated by spaces using JavaScript
- Generating Random String Using PHP
- Generating a unique random 10 character string using MySQL?
- Finding the length of longest vowel substring in a string using JavaScript
- MySQL number-string formatting to pad zeros on the left of a string with numbers after a slash
- Constructing a string of alternating 1s and 0s of desired length using JavaScript
- Breaking a string into chunks of defined length and removing spaces using JavaScript
- Right pad a string in Java
- Left pad a string in Java

Advertisements