The Wayback Machine - https://web.archive.org/web/20241004131839/https://www.geeksforgeeks.org/random-string-generator-using-javascript/
Open In App

Random String Generator using JavaScript

Last Updated : 26 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

JavaScript is a lightweight, cross-platform, interpreted scripting language. It is well-known for the development of web pages, many non-browser environments also use it. JavaScript can be used for Client-side developments as well as Server-side developments.

In this article, we need to create a Random String Generator using Javascript that will generate a random set of strings & get displayed when the user clicks a button. Additionally, we can also take input for the length of the string from the user. On the client-side, it will render those strings once generated using the Document Object Model (DOM) concept.

Approach: For generating Random Strings in Javascript, we can use in-built methods that will actually generate the strings and can manipulate the Document Object Model (DOM) accordingly. We will use the Math library to access the random() function that will help to generate the random index and multiple with the length of the string ie., it will append the character from the string or character set as it is passed. 

We can generate the random string in 2 ways ie., either we can iterate the loop for the specified length of the character set or we can use String.fromCharCode() method that will convert the UTF-16 codes into their equivalent characters and returns the string. By using the 2nd approach, we can manually take input for the length of the string from the user then generate the string of that particular length by accessing the DOM elements. For both approaches, we will use the Math.random() function.

Generating Random Strings: Here, we will generate strings only with lowercase letters characters. Let’s start by discussing the two different approaches for generating the strings.

Approach 1: Generating the random string from the specified length of the character set:

  • Declare the character set that will use for generating string.
  • Access the length of that character set from the input.
  • Construct the iteration loop for random character generation.
  • Use Math functions in javascript & assign them to the variable.

We will utilize the above concepts & generate the strings randomly of user-defined length using Javascript and DOM manipulation.

Defining the character set: We have defined a variable “characters” that will contain all the characters as we require. We will use another variable “result” which is initialized as an empty string.

Accessing the length of the string: After this, we will fetch the length of the string that we need to generate by using the document.getElementById method to access the HTML element or the user input field that contains the length.

length = document.getElementById("strlength").value;

So, we have used the “strlength” id which is declared inside the  HTML <input> tag. We can get the value of the element using the “.value” attribute and then assign it to a “length” variable. Thus, we have now obtained the length of the string that is needed to generate.

Generating Random characters: We will use a for loop to generate n(length) number of characters and append those to the string. The loop will run from 0 till length -1 as the index value start from 0.

for ( let i = 0; i < length; i++ ) {
// Code
}

Now, we will use the Math.random() function to generate a random index in the string. Before that, we need to get the length of the “characters” string and store it in a const variable “charactersLength”. This will give us the length of the “charactersLength” string which is 26. Now, using the charAt() function that will return the character at a specified index in a string & we can get the random number.

The Math.random() function will give the value between 0 & 1 ie., decimal value & we need to round it off to get an integer value. Hence, we use Math.floor to round off the decimal value. We will multiply the Math.random() function with the variable charactersLength, to get the exact integer value. Thus, this will give us an integer between 0 and characterslength-1. 

Math.floor(Math.random() * charactersLength)

The above syntax will give the integer between 0 and the length of the charactersLength-1 as the strings in Javascript are 0 based indexing.

Hence, by using characters.charAt() method, we can get the character at that particular index. We finally add it to the empty string “result” and at the end of the loop, we get a string with random characters.

Example: This example describes the random number generation for the specified length of the character.

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>String Generator</title>
</head>

<body>
    <h2>Random String Generator</h2>
    <h4 id="target"></h4>
    <input id="strlength" type="number" value="5" min="1" max="100" />
    <button id="gen" onClick="generate()">Generate</button>
    
    <script>
    function generate() {
        let length = document.getElementById("strlength").value;
        const characters = 'abcdefghijklmnopqrstuvwxyz';
        let result = ' ';
        const charactersLength = characters.length;
        for(let i = 0; i < length; i++) {
            result += 
            characters.charAt(Math.floor(Math.random() * charactersLength));
        }
        document.getElementById("target").innerHTML = result
    }
    </script>
</body>

</html>

Output:

Approach 2: Generating the random string by using the String.fromCharCode() function:

  • Fetch the length of the string to be generated from the input.
  • Construct the iteration loop for the random character generation.
  • Use String and Math functions to generate characters.

We can use in-built functions like String.fromCharCode() function to generate a random Character. The step for declaring the character set & accessing its length will be similar to the first approach ie., we will create the length variable to get the length of the user input. After that, we create an empty string “result” for storing the generated string. We then run a for loop to iterate over the length of the string.

for ( let i = 0; i < length; i++ ) {
// Code
}

Now, we use the function String.fromCharCode to generate characters one by one using the for loop. The String.fromCharCode takes in the integer or UTF-16 code units and gives the equivalent string. Here, we are using the integer 97 i.e. the starting point of lowercase letters. You can refer to the UTF-16 table to get the value of the lower case letters. So, getting that lowercase ‘a’ is 97 in UTF-16, we can add 26 to the number to get the last letter ‘z’ as 122. So, we simply need to generate 26 random numbers and add them to 97.

We can use the Math.random() function that returns a value between 0 and 1 and to get the integer value we need to floor() function to get the exact integer value & hence, we use the Math.floor(). But this will only get us 0 , every time we need to multiply the number Math.random() with 26 to get that desired result. 

97 + Math.floor(Math.random() * 26)

This will give the value between 97 and 122 i.e. ‘a’ to ‘z’. Thus, by enclosing them in the function String.fromCharCode() to get the actual string.

Displaying the generated Strings: We have displayed the string using the innerHTML property and by accessing the HTML element using its id value. So, using the “document.getElementById” method to get the element h4 with the id “target” from the HTML code and then access the HTML value using “.innerHTML”. We assign that value to the string “result” which is the randomly generated string. This will display the string in the HTML template.

document.getElementById("target").innerHTML = result;

Example: This example describes the random number generation using the String.fromCharCode() function.

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>String Generator</title>
</head>

<body>
    <h2>Random String Generator</h2>
    <h4 id="target"></h4>
    <input id="strlength" type="number" value="5" min="1" max="100" />
    <button id="gen" onClick="generate()">Generate</button>
    
    <script>
    function generate() {
        let length = document.getElementById("strlength").value;
        let result = ' ';
        for(let i = 0; i < length; i++) {
            result += 
            String.fromCharCode(97 + Math.floor(Math.random() * 26));
        }
        document.getElementById("target").innerHTML = result
    }
    </script>
</body>

</html>

Output:



Similar Reads

Design Random Color Generator using HTML CSS and JavaScript
The Random Color Generator application can Generate new and random colors each time the user clicks on the Generate Color button. The user has the feature to Copy the HEX and RGB code of the generated color for the application. There is Dark Mode functionality, through which the user can view the generated color in the Dark Mode also and can toggle
4 min read
Random Quote Generator Using HTML, CSS and JavaScript
A Random Quote Generator is capable of pulling quotes randomly from an API, a database, or simply from an array. We will be designing a Random Quote Generator from scratch using HTML, CSS, JavaScript, and type.fit API. The webpage displays a random quote from a collection and upon the click of a button, it randomly generates a new quote. We will fi
8 min read
Random Image Generator using JavaScript
In this article, we will learn how to generate random images in fixed intervals using only HTML, CSS, and JavaScript. Approach: The pictures which are going to be generated randomly on the website should be stored in the form of an array, these pictures are then displayed to the user within a regular time interval. We use the setInterval() function
4 min read
Build Random Quote Generator using VueJS
We are going to build a Random Quote Generator using Vue.js. This application will fetch random quotes from an API and display them on the screen. Users will have the option to copy the quote to their clipboard or generate a new random quote. Prerequisites:Node.jsVue.jsApproachWe'll create a Vue.js component called QuoteGenerator that fetches rando
4 min read
Create a Random Quote Generator using React-Native
React Native is the most flexible and powerful mobile application development framework, which has various features embedded into it. Using this framework, we can create different interactive applications. Creating a Random Quote Generator using React Native is one of the interactive project which utilizes the API to generate the random quote and p
4 min read
Build a Random Name Generator using ReactJS
In this article, a Random Name Ge­nerator will be created using React.js. Building a Random Name Generator means creating a program or application that generates random names, typically for various purposes like usernames, fictional characters, or data testing. It usually involves combining or selecting names from predefined lists or patterns. Prer
4 min read
Build a Random User Generator App Using ReactJS
In this article, we will create a random user generator application using API and React JS. A Random User Generator App Using React Js is a web application built with the React.js library that generates random user profiles. It typically retrieves and displays details like names, photos, and contact information to simulate user data for testing and
4 min read
Random Quote Generator App using ReactJS
In this article, we will create an application that uses an API to generate random quotes. The user will be given a button which on click will fetch a random quote from the API and display it on the screen. Users can generate many advices by clicking the button again. The button and the quotes are displayed beautifully using CSS styling to create a
3 min read
Create a Random User Generator using jQuery
With the use of the API and jQuery, we'll create a random user generator app. A straightforward web application called "jQuery Random User Generator" makes use of jQuery and the RandomUser.me API to generate random user data and present it in a visually appealing way. Users of this project can click a button to get random user information, such as
3 min read
Design a Random Quote Generator in Tailwind CSS
This project demonstrates the creation of a simple Random Quote Generator web application using HTML, Tailwind CSS for styling, and JavaScript for functionality. The application generates random quotes and their authors upon clicking the "Generate Quote" button, offering an interactive and visually appealing experience. Prerequisites / Technologies
3 min read
Build a Random Number Generator in Tailwind CSS
A Random Number Generator (RNG) is a tool that generates a random number within a specified range. By combining Tailwind CSS's utility classes with JavaScript, you can create a simple and visually appealing RNG that can be easily integrated into any web application. Approach:Create an HTML file and include the necessary Tailwind CSS CDN link in the
2 min read
Create an QR Code Generator Project using HTML CSS & JavaScript
In today's digital world, QR codes are widely used and provide a practical way to share information and access content with a quick scan. This deeply manually operated will show you step-by-step how to create a QR code generator from scratch using HTML, CSS, and JavaScript. This article will give you the knowledge necessary to develop an intuitive
3 min read
Number Sequences Generator using HTML CSS and JavaScript
In this article, we are going to implement a number sequence generator based on HTML, CSS, and JavaScript. In this program, we have three different types of sequences: the Fibonacci Series, the Prime Number Series, and the Even Odd Number Series. Preview of final output: Let us have a look at how the final output will look like. PrerequisitesHTMLCS
5 min read
YouTube Video Embed Code Generator Tool using HTML CSS and JavaScript
In this article, we will see How to create your own YouTube Video embed code generator tool using the basics of HTML, CSS, and JavaScript. With this tool, we can create responsive embed code for responsive video output on all devices. We can make use of this tool and add the generated code in Blogger, WordPress, Wix, Google Sites, custom websites,
4 min read
OTP Generator and Validator Card using JavaScript & Tailwind CSS
OTP (One-Time Password) generator and validator built using Tailwind CSS and JavaScript allows users to generate a random OTP and validate it against the entered OTP. The application has a user-friendly interface for generating and validating OTPs using JavaScript for interactivity and Tailwind CSS for styling. Approach to create OTP Generator and
3 min read
Wikipedia Summary Generator Card using Tailwind CSS & JavaScript
The Wikipedia Summary Generator is a web application that utilizes Tailwind CSS, enabling users to search for a topic and receive a summary from Wikipedia. Users can input their topic of choice into the application's search field, click on the "Search" button to retrieve the summary, and then download the summary as a text file. In addition, the ap
3 min read
How to create Password Generator Card using JavaScript and Tailwind CSS ?
The Password Generator is a web application built using Tailwind CSS and JavaScript. It allows users to generate random passwords based on their specified criteria such as the length and character types. Output Preview: Let us have a look at how the final card will look like. ApproachIntegrate the Tailwind CSS via CDN Link in your HTML code. Use di
3 min read
Color Pallete Generator using JavaScript
Color Palette Generator App using HTML CSS and JavaScript is a web application that enables use­rs to effortlessly gene­rate random color palettes, vie­w the colors, and copy the color codes to the­ clipboard with just a single click. There is also a search bar that allows the user to check different color themes for their specified color. Prerequi
4 min read
Navigating the Labyrinth: A Maze Generator Game Using HTML CSS & JavaScript
This article will help you make a simple yet interesting maze game, combining the power of HTML, CSS, and JavaScript to immerse the players. Let's explore the development of a maze generator game, where players can navigate through a new labyrinth with each refresh, thanks to the implementation of a Backtracking Algorithm. Preview Image: Approach:T
11 min read
Create a Quote Generator Web App with Pure JavaScript using an API
In this tutorial we are going to create a web app that fetches motivational and inspirational quotes using an API. Application Requirements: Bootstrap 4 CDNAPI : https://type.fit/api/quotesJavaScriptHTMLSteps: Follow the below steps to create a quote generator. Step 1 Fetch: We are using inbuilt fetch Function of JavaScript for fetching the data fr
3 min read
How to create a Color Generator using HTML CSS and JavaScript ?
In this article, we will develop a Color Generator application using HTML, CSS, and JavaScript. In this application, we have created the Multi Format color generator. Users can select Colour Types like RGB, HEX, and CMYK. Use the sliders to customize the color and Inout field in case of HEX and color picker to directly change the color with color i
6 min read
How to Check a Function is a Generator Function or not using JavaScript ?
Given an HTML document containing some JavaScript function and the task is to check whether the given function is generator function or not with the help of JavaScript. There are two examples to solve this problem which are discussed below: Example 1:In this example, we will use functionName.constructor.name property. It functionName.constructor.na
2 min read
How to create RGB color generator using HTML CSS and JavaScript ?
In this article, we will create a RGB color generator using HTML, CSS, and JavaScript. Using RGB color generator, we can construct all the colors from the combination of Red, Green, Blue colors. Each color is represented by the range of decimal numbers from 0 to 255 (256 levels for each color). So, the total number of available colors is 256 x 256
3 min read
How to create Hex color generator using HTML CSS and JavaScript?
Hex color codes are six-digit combinations representing the amount of red, green, and blue (RGB) in a color. These codes are essential in web design and development for specifying colors in HTML and CSS. The hex color generator provides the hex code for any selected color, making it a valuable tool for designers and developers. Approach to Generati
2 min read
How to create linear-gradient color generator using HTML, CSS and JavaScript ?
Creating a background generator using HTML, CSS, and JavaScript is an excellent way to add interactive and visually appealing features to your web projects. This tool allows users to generate gradient backgrounds based on their selected color values. In this article, we'll walk you through the steps to build a background generator, including settin
2 min read
Create a Emoji Generator Using HTML CSS & JavaScript
While communicating with our friends, we always use the emoji to represent our feelings and emojis. There are many emojis that represent our emotions and feelings. As developers, we can generate a random emoji on every click of the button, and we can also copy that emoji and paste it into our chat box or in the messaging area. This project has HTML
7 min read
Captcha Generator using HTML CSS and JavaScript
A captcha is a way of identifying a user whether the user is human or not. A captcha is made up with the help of combining letters and digits. it ensures that the user who is trying to access the platform is a human. So without wasting the time let's get started. Application of CaptchaForm Authentication: For login and sign up it can be used to ens
3 min read
Generate random alpha-numeric string in JavaScript
In this article with the help of javascript we are generating the alpha-numeric string of specific length using javascript, here are some common method Approach 1: Creates a function that takes 2 arguments one is the length of the string that we want to generate and another is the characters that we want to be present in the string.Declare new vari
2 min read
JavaScript Generator throw() Method
JavaScript Generator.prototype.throw() method is an inbuilt method in JavaScript that is used to resume the execution of a generator by throwing an error into it. Syntax: gen.throw(exception); Parameters: This function accepts a single parameter as mentioned above and described below: exception: This parameter holds the exception to be thrown. Retu
2 min read
JavaScript Generator return() Method
JavaScript Generator.prototype.return() method is an inbuilt method in JavaScript that is used to return the given value and finishes the generator. Syntax: gen.return( value ); Parameters: This method accepts a single parameter as mentioned above and described below: value: This parameter holds the value to be returned. Return value: This method r
2 min read