how to create unique alphanumeric string using javascript
Here, I will be explaining different methods for creating a unique alphanumeric string using javascript
Method 1
1 |
Math.random().toString(36).substring(2, 15) |
The toString() method returns a string representing the specified Number object, where the Number can range between 2 and 36.
The above example first gives a random number, like this 0.5962055277407441
This random number then parsed to a string using toString method which attempts to return a string representation in the specified radix (base). Here, we get a string like this “0.lgokcdetg2”
Now we take a substring of the above result.
ie; “0.lgokcdetg2”.substring(2, 15)
which results in lgokcdetg2
And, we can make even bigger strings by concatenating the same formula.
1 |
Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15); |
Method 2
This is a slight variation of Method 1
1 |
Math.random().toString(36).slice(2) |
Leave a Reply