Generate random string in JavaScript
If you are coding in JavaScript and there are some need to Generate random string then how to Generate random string in JavaScript ?
Here is the few lines of code that is generate random String in JavaScript.
const myRndStr = () => Math.random().toString(36).slice(2)
const sstr1= myRndStr();
console.log(sstr1);
const sstr2= myRndStr();
console.log(sstr2);
const sstr3= myRndStr();
console.log(sstr3);
OUTPUT
Explanation:
In Math.random().toString() you can pass number 36. It is max limit number and you can not pass greater than 36 number. So it will generate a string like "0.1vjydtyngt58" Now you can get all string after that "0.1" using function ".slice(2)" as Math.random().toString(36).slice(2). Then you will get something like this "vjydtyngt58"
If you will pass greater than 36 number then you will see error
message "Uncaught RangeError: radix must be an integer at least 2 and no
greater than 36"
I have used arrow operator ()=> to generate random string. We can also create it in Vanilla JavaScript as below:
function genRndStr(){
return Math.random().toString(36).slice(2);
}
const str4=genRndStr()
console.log(str4);