I want to create a random string (token) which can be used to identify a user whilst avoiding any potential conflicts with any other users\' tokens.
What I was thinking
This function allows you to set the token length and allowed characters.
function generate_token(length){
//edit the token allowed characters
var a = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".split("");
var b = [];
for (var i=0; i<length; i++) {
var j = (Math.random() * (a.length-1)).toFixed(0);
b[i] = a[j];
}
return b.join("");
}
Simply call generate_token
generate_token(32); //returns "qweQj4giRJSdMNzB8g1XIa6t3YtRIHPH"
Checkout crypto.js project. Its a collection of cryptographic algorithms. The project has separate js files for each hashing algorithms.
//length: defines the length of characters to express in the string
const rand=()=>Math.random(0).toString(36).substr(2);
const token=(length)=>(rand()+rand()+rand()+rand()).substr(0,length);
console.log(token(40));
//example1: token(10) => result: tsywlmdqu6
//example2: token(40) => result: m4vni14mtln2547gy54ksclhcv0dj6tp9fhs1k10
You could generate a random number and convert it to base 36 (0-9a-z
):
var rand = function() {
return Math.random().toString(36).substr(2); // remove `0.`
};
var token = function() {
return rand() + rand(); // to make it longer
};
token(); // "bnh5yzdirjinqaorq0ox1tf383nb3xr"
I use an approach similar to Kareem's, but with fewer function calls and built-in array operations for a big boost in performance.
According to a performance test, this method also outperforms the accepted answer by a small margin. Moreover it provides a parameter n
to generate any size token length from a white list of acceptable characters. It's flexible and performs well.
function generateToken(n) {
var chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
var token = '';
for(var i = 0; i < n; i++) {
token += chars[Math.floor(Math.random() * chars.length)];
}
return token;
}
It is very unlikely, but Math.random() could return 0.0
. In that case, the solution of pimvdb would return ""
(empty string). So, here is another solution, which returns in every case a random base36 with 10 chars length:
function generateToken() {
Math.floor(1000000000000000 + Math.random() * 9000000000000000)
.toString(36).substr(0, 10)
}