How To Generate Random String Characters In JavaScript

How To Generate Random String Characters In JavaScript

In this tutorial, you’ll learn how to generate random string characters in JavaScript. I’ll follow a simple approach to generate a random string based on the length passed to a JavaScript function.

Generate Random String Characters Using Small Letters

The ascii code for a to z is 97 to 122. So, the logic will be to select random ascii code from 97 to 122 and create random string character based on the length of the string.

function generate_random_string(string_length){
    let random_string = '';
    let random_ascii;
    for(let i = 0; i < string_length; i++) {
        random_ascii = Math.floor((Math.random() * 25) + 97);
        random_string += String.fromCharCode(random_ascii)
    }
    return random_string
}

console.log(generate_random_string(5))

Random number between a particular range can be generated using Math.random function.

Generate Random String Characters Using Capital Letters

Random string characters in JavaScript using capital letters can be accomplished similarly by selecting random characters between 65 and 90. The code for the same is :

function generate_random_string(string_length){
    let random_string = '';
    let random_ascii;
    let ascii_low = 65;
    let ascii_high = 90
    for(let i = 0; i < string_length; i++) {
        random_ascii = Math.floor((Math.random() * (ascii_high - ascii_low)) + ascii_low);
        random_string += String.fromCharCode(random_ascii)
    }
    return random_string
}

console.log(generate_random_string(5))

The output of the above code will be a random string like YPIGH.

Generate Random Alphanumerics Characters In JavaScript

To generate random alphanumeric characters in JavaScript you’ll need to generate random number from 0 to 9 and alphabets from 65 to 90 or 97 to 122. Here is how the code looks :

function generate_random_string(string_length){
    let random_string = '';
    let random_ascii;
    let ascii_low = 65;
    let ascii_high = 90
    for(let i = 0; i < string_length; i++) {
        random_ascii = Math.floor((Math.random() * (ascii_high - ascii_low)) + ascii_low);
        random_string += String.fromCharCode(random_ascii)
    }
    return random_string
}

function generate_random_number(){
    let num_low = 1;
    let num_high = 9;
    return Math.floor((Math.random() * (num_high - num_low)) + num_low);
}

function generate() {
    return generate_random_string(3) + generate_random_number()
}

console.log(generate())

Wrapping It Up

In this tutorial, you learnt how to generate random string characters in JavaScript. Have you ever used a different approach to generate random string in JavaScript ? Do let us know your thoughts in the comments below.