How to Generate random alpha-numeric string using javascript

Generating random alpha-numeric string by javascript or jQuery can be achieved very easily because it requires some built in functions and basic knowledge only. Random alpha-numeric string by javascript is a series of numbers and letters that have no pattern. These can be helpful for creating security codes.

There are so many ways to generate random alpha-numeric string by Javascript, so here we’ll go with a simple method.

This method which is fully depends on specifications.

Here we’ll generate random alpha-numeric string by Javascript using strings, characters, symbols and numeric along with the Math.random() function.

Explanation :

This method first generate a random number(0-1) and then takes the character from the set of characters which we are specifying.

  1. Create a function called generateString() which accepts parameter length. The length parameter is given to return a string with the specified length.
  2. The result variable is to store the final result, and characters is to get a custom string. In this example I am using alphabets, numbers and symbols.
  3. Take the length of characters and store to charactersLength.
  4. Inside a for loop :
    1. store the values to result variable.
    2. charAt () method will return the character at the specified index. Indexing start with 0, like the index of first character will be 0, second is 1, third is 2 and so on.
    3. Math.floor() will return the largest value that is less than or equal to a number. In other words, the floor() function rounds a number down and returns an integer.
    4. Math.random() is used to return a floating-point, pseudo-random number in the range 0 to less than 1 (inclusive of 0, but not 1).
    5. Generate a random number, multiply it with the total length of characters then round the result and get the character at the specifeid number(index) from the set of characters which we declared initially.

Javascript

function generateString(length) 
{
     var result           = '';
     var characters       = 
     'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_+=-';
     var charactersLength = characters.length;
     for ( var i = 0; i < length; i++ ) 
     {
          result += characters.charAt(Math.floor(Math.random() * charactersLength));
     }
     return result;
}
console.log(generateString(10));

This may not be the best method because there are so many methods to generate random strings by javascript, but you can use this method because it will work 100%.

jQuery : https://code.jquery.com/jquery-1.9.1.min.js

For jQuery related solutions please visit jQuery

Leave A Comment