Generate random string/characters in JavaScript

前端 未结 30 1783
闹比i
闹比i 2020-11-21 06:34

I want a 5 character string composed of characters picked randomly from the set [a-zA-Z0-9].

What\'s the best way to do this with JavaScript?

30条回答
  •  盖世英雄少女心
    2020-11-21 07:25

    The most compact solution, because slice is shorter than substring. Subtracting from the end of the string allows to avoid floating point symbol generated by the random function:

    Math.random().toString(36).slice(-5);
    

    or even

    (+new Date).toString(36).slice(-5);
    

    Update: Added one more approach using btoa method:

    btoa(Math.random()).slice(0, 5);
    btoa(+new Date).slice(-7, -2);
    btoa(+new Date).substr(-7, 5);
    

    // Using Math.random and Base 36:
    console.log(Math.random().toString(36).slice(-5));
    
    // Using new Date and Base 36:
    console.log((+new Date).toString(36).slice(-5));
    
    // Using Math.random and Base 64 (btoa):
    console.log(btoa(Math.random()).slice(0, 5));
    
    // Using new Date and Base 64 (btoa):
    console.log(btoa(+new Date).slice(-7, -2));
    console.log(btoa(+new Date).substr(-7, 5));

提交回复
热议问题