Generate random string/characters in JavaScript?


Scripting in JavaScript is simple, cross-platform, and lightweight. It is widely used in nonbrowser situations and is well known for web page building. Both client-side and serverside development can be done with JavaScript.

JavaScript has built-in methods that can be used to generate random strings and modify the Document Object Model (DOM) in accordance with our needs. The random() function, which helps to generate the random index and multiple with the length of the string, will be accessed through the Math library. It will append the character from the string or character set as it is passed.

Create a Custom method to generate random string

A unique method can be developed to produce random strings. Here, the terms, numbers, and special characters are defined. To create a random string, simply call this JavaScript function whenever you want.

Example

In the following example we are generating a random string using custom method.

<!DOCTYPE html>
<html>
<script>
   function genRandonString(length) {
      var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()';
      var charLength = chars.length;
      var result = '';
      for ( var i = 0; i < length; i++ ) {
         result += chars.charAt(Math.floor(Math.random() * charLength));
      }
      return result;
   }
   document.write(genRandonString(4));
</script>
</html>

When the script gets executed, the event gets triggered and displays a random string consisting of length 4 from the given character set in the above script on the web-browser. Its four string values change as long as the user runs the script.

Example

Consider the following example, where we are creating a random function.

<!DOCTYPE html>
<html>
<script>
   const characters ='TUTORIALPOINTABCDEF01234GHIJ56789';
   function generateString(length) {
      let result = ' ';
      const charactersLength = characters.length;
      for ( let i = 0; i < length; i++ ) {
         result += characters.charAt(Math.floor(Math.random() * charactersLength));
      }
      return result;
   }
   document.write(generateString(4));
</script>
</html>

On running the above script, the event gets triggered and displays a string generated randomly of length 4 on the web-browser. As long as the user generates the script, it will produce different random strings on the output window.

Math.random() method to generate random string

The pseudorandom number between 0 and 1 is the result of the Math.random() method. Strings are denoted in JavaScript by a group of characters enclosed in double quotes (""). Since strings are merely collections of characters, we can create a random string using the Math.random() method.

Syntax

Following is the syntax for Math.random()

Math.random()

Example

Considering the following example where we are using the Math.random() to generate random string.

<!DOCTYPE html>
<html>
<script>
   function stringGen(len) {
      var text = "";
      var charset = "abcdefghijklmnopqrstuvwxyz23456789";
      for (var i = 0; i < len; i++)
      text += charset.charAt(Math.floor(Math.random() * charset.length));
      return text;
   }
   document.write(stringGen(2));
</script>
</html>

On running the above script, the output window will pop up, displaying the random string generated of length 2 on the webpage. This is because the event gets triggered as soon as the user runs the script, and it will produce a different random string as long as the user runs the script.

Example

Let’s look into the another example, where we are using the Math.random()

<!DOCTYPE html>
<html>
<script>
   function generateRandomNumber(numberOfCharacters) {
      var randomValues = '';
      var stringValues = 'ABCDEFGHIJKLMNOabcdefghijklmnopqrstuvwxyzPQRSTUVWXYZ';
      var sizeOfCharacter = stringValues.length;
      for (var i = 0; i < numberOfCharacters; i++) {
         randomValues = randomValues+stringValues.charAt(Math.floor(Math.random() * sizeOfCharacter));
      }
      return randomValues;
   }
   document.write(generateRandomNumber(6));
</script>
</html>

When the script gets executed, it will generate an output consisting of a string of length 6 on the web-browser, because the event gets triggered and display the different random string as long as the user executes the script.

Updated on: 18-Jan-2023

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements