Create Random Strings Using JavaScript

Introduction

In this blog, we will discuss how to create a Random String using Javascript that will generate a variety of random strings. On click on the button.

<h2>Random String In JavaScript</h2>
    <p id="random"></p>
    <button id="buttonId" onClick="random()">clickme</button>
?<script>
    function random() {
        let result = ' ';
        for(let i = 0; i < 6; i++) {
            result +=
            String.fromCharCode(97 + Math.floor(Math.random() * 26));
        }
        document.getElementById("random").innerHTML = result
    }
   </script>
?

Markup

Copy

Create a function in javascript as random(). In this function, we declare one variable empty result and then start for loop from i=0 to i is less than 6. Now, we'll create a random index in the string using the Math.random() function. Prior to that, we must obtain the character's string's length and store it in a const variable called charactersLength. which is 26. We can now obtain the random number by using the charAt() method, which returns the character located at the provided index in a string. The Math.random() function returns a decimal value, between 0 and 1, and we must round it to an integer value. So, to round off the decimal value, we utilize Math.floor. To obtain the precise integer value, we shall multiply the Math.random() function by the variable charactersLength. We will thus receive an integer between 0 and characterslength-1 as a result.

Output

Create Random Strings Using JavaScript

Conclusion

This is how we can create a random String or character and use it in JavaScript.

Thanks, I hope this will help you.

Ebook Download
View all
Learn
View all