Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Generating random string of specified length in JavaScript
We are required to write a JavaScript function that takes in a number n and returns a random string of length n containing no other than the 26 English lowercase alphabets.
Therefore, let's write the code for this function ?
Example
The code for this will be ?
const num = 8;
const randomNameGenerator = num => {
let res = '';
for(let i = 0; i
Output
The output in the console will be ?
kdcwping
Note ? This is one of many possible outputs. Console output is expected to differ every time.
How It Works
The function uses Math.random() to generate random numbers between 0 and 25, then converts them to lowercase letters using String.fromCharCode(97 + random), where 97 is the ASCII code for 'a'.
Alternative Method Using Array
Here's another approach using an array of characters:
const generateRandomString = (length) => {
const chars = 'abcdefghijklmnopqrstuvwxyz';
let result = '';
for (let i = 0; i
mjkhtqpwxy
vlnoc
Conclusion
Both methods effectively generate random lowercase strings. The ASCII approach is more compact, while the character array method is more readable and easier to modify for different character sets.
