As you may already know, the easiest way to generate random decimal numbers in javascript is to use this line of code in your js:


//out put would look like

 What if you want to get rid of "0." from the numbers, you can do that like this in your javascript code:

Math.random().toString().replace('0.', '') 

//out put would look like

If you are just looking to generate a random numbers, this would do the trick for you.

If you are looking to generate random alphanumeric string in javascript, you have plenty of options. 

For example, if you just wanted to add the letter "a" to your js random string, you can do it like this:

Math.random().toString(11).replace('0.', '') 

//out put would look like

The javascript function ".toString()" does accept a parameter range from 2 to 36. Numbers from 2 to 10 represent: 0-9 values and 11 to 36 represent alphabets. 

If you wanted to include alphabets (a-c), you would just change "11" to "13"

Math.random().toString(13).replace('0.', '') 

//out put would look like

Alphanumeric random string in javascript

To ensure you have completely random alphanumeric string without repetition in your js, I would recommend you use all the alphabets.

Math.random().toString(36).replace('0.', '') 

//out put would look like

You can put this in a function and call it from your javascript file.

//option 1 	
var random_id_1 = function  () 
  return Math.random().toString(36).substr(2);

//option 2
var random_id_2 = function  () 
  return Math.random().toString(36).replace('0.', '') ;






Post Comment