# [Solved-6 Solutions]Generate random string/characters in JavaScript - javascript tutorial

## Problem:

How to generate random string/characters in JavaScript ?

## Solution 1:

• To create a random sequence of numbers and/or text. The function which generates the random string can be called from any event handler.

## Step 1

To set the variables,

• chars
• The random string will be created from these characters.
• string_length
• The length of the random string.

## Step 2

• Use the following code for your text field and button

## Solution 3:

Generating Random whole number in javascript

## Solution 4:

Method 1

If we're able to do this server-side, just use the crypto module

The resulting string will be twice as long as the random bytes you generate; each byte encoded to hex is 2 characters. 20 bytes which means 40 characters of hex.

Method 2

If we have to do this client-side, perhaps try the uuid module

Method 3

If we have to do this client-side and we don't have to support old browsers, we can do it without dependencies

## Solution 5:

A small probability producing short strings or even an empty string (if the random number is 0), which may break your application. Here is a solution:

Second, both the original and the solution above limit the string size N to 16 characters. The following will return a string of size N for any N (but note that using N > 16 will not increase the randomness or decrease the probability of collisions):

Explanation:

• Pick a Random number in the range [0,1], i.e. between 0 (inclusive) and 1 (exclusive).
• Convert the number to a base-36 string, i.e. using characters 0-9 and a-z.
• Pad with zeros (solves the first issue).
• Slice off the leading zeros, i.e. prefix and extra padding zeros.
• Repeat the string enough times to have at least N number of characters in it (by Joining empty strings with the shortest random string used as the delimiter).
• Slice exactly N characters from the string.