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?
We started with Q&A. Technical documentation is next, and we need your help.
Whether you're a beginner or an experienced developer, you can contribute.
I want a 5 character string composed of characters picked randomly from the set What's the best way to do this with JavaScript? |
||||
I think this will work for you:
|
|||||||||||||||||||||
|
|
|||||||||||||||||||||
|
Here's an improvement on doubletap's excellent answer. The original has two drawbacks which are addressed here: First, as others have mentioned, it has a small probability of producing short strings or even an empty string (if the random number is 0), which may break your application. Here is a solution:
Second, both the original and the solution above limit the string size N to 16 characters. The following will return a string of size N for any N (but note that using N > 16 will not increase the randomness or decrease the probability of collisions):
Explanation:
Further thoughts:
Update: Here are a couple other functional-style one-liners I came up with. They differ from the solution above in that:
So, say your alphabet of choice is
Then these two are equivalent to each other, so you can pick whichever is more intuitive to you:
and
Edit: I seems like qubyte and Martijn de Milliano came up with solutions similar to the latter (kudos!), which I somehow missed. Since they don't look as short at a glance, I'll leave it here anyway in case someone really wants a one-liner :-) Also, replaced 'new Array' with 'Array' in all solutions to shave off a few more bytes. |
|||||||||||||||||||||
|
Something like this should work
Call with default charset [a-zA-Z0-9] or send in your own:
|
|||||||||||||
|
alert(randomstring(5)) |
|||||||||||||||||
|
Math.random is bad for this kind of thing Option 1 If you're able to do this server-side, just use the crypto module
The resulting string will be twice as long as the random bytes you generate; each byte encoded to hex is 2 characters. 20 bytes will be 40 characters of hex. Option 2 If you have to do this client-side, perhaps try the uuid module
Option 3 If you have to do this client-side and you don't have to support old browsers, you can do it without dependencies
Ok, let's check it out !
Browser requirements
|
|||||||||||||||||||||
|
The simplest way is:
This generate random strings of 5 characters based on the current time. Example output is The problem with this is that if you call it two times on the same second, it will generate the same string. The safer way is:
This will generate a random string of 4 or 5 characters, always diferent. Example output is like In both ways the first part generate a random number. The |
|||||||||||||||||
|
The most compact solution, because
or even
|
||||
|
Random String Generator (Alpha-Numeric | Alpha | Numeric)
Have fun. jsBin demo While the above uses additional checks for the desired (A/N, A, N) output, let's break it down the to the essentials (Alpha-Numeric only) for a better understanding:
Let's picture the Character table and their ranges:
The conditional operation logic from the table above:
If you followed the above explanation you should be able to create this alpha-numeric snippet:
|
||||
|
Here are some easy one liners. Change Including
|
Short and easy + returns exactly 5 random characters, as opposed to some of the top rated answers found here.
|
|||||
|
I know everyone has got it right already, but i felt like having a go at this one in the most lightweight way possible(light on code, not CPU):
It takes a bit of time to wrap your head around, but I think it really shows how awesome javascript's syntax is. |
|||||||||
|
In case anyone is interested in a one-liner (although not formatted as such for your convenience) that allocates the memory at once (but note that for small strings it really does not matter) here is how to do it:
You can replace |
|||||||||
|
Here's the method I created. Working examples:
Upgrade July 2015
|
|||||||||
|
Assuming you use underscorejs it's possible to elegantly generate random string in just two lines:
|
|||
|
You can loop through an array of items and recursively add them to a string variable, for instance if you wanted a random DNA sequence:
|
|||
|
This works for sure
|
|||
|
This is as clean as it will get. It is fast too, http://jsperf.com/ay-random-string. |
|||||||||
|
I loved the brievety of doubletap's Math.random().toString(36).substring(7) answer, but not that it had so many collisions as hacklikecrack correctly pointed out. It generated 11-chacter strings but has a duplicate rate of 11% in a sample size of 1 million. Here's a longer (but still short) and slower alternative that had only 133 duplicates in a sample space of 1 million. In rare cases the string will still be shorter than 11 chars:
|
|||
|
Generate 10 characters long string. Length is set by parameter (default 10).
|
||||
|
How about this compact little trick?
You need the |
|||
|
If a library is a possibility, Chance.js might be of help: http://chancejs.com/#string |
|||
|
Here is a test script for the #1 answer (thank you @csharptest.net) the script runs note: node stack size limit exceeds around 4 million so you cant run this 5 million times it wont ever finish.
|
|||
|
If you are using Lodash or Underscore, then it so simple:
|
|||||
|
A functional approach. This answer is only practical if the functional prerequisites can be leveraged in other parts of your app. The performance is probably junk, but it was super fun to write.
In my opinion, it's hard to beat the clarity of A slight improvement could be
Have fun with it. Let me know what you like/learn ^_^ |
|||||
|
Expanding on Doubletap's elegant example by answering the issues Gertas and Dragon brought up. Simply add in a while loop to test for those rare null circumstances, and limit the characters to five.
Here's a jsfiddle alerting you with a result: http://jsfiddle.net/pLJJ7/ |
|||
|
will generate a random alpha-numeric string with the length of the first/calling string |
|||||
|
This is what I used. A combination of a couple here. I use it in a loop, and each ID it produces is unique. It might not be 5 characters, but it's guaranteed unique.
|
|||||
|
|
|||||
|
Also based upon doubletap's answer, this one handles any length of random required characters (lower only), and keeps generating random numbers until enough characters have been collected.
|
|||
|
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
true-random
result! They are onlypseudo-random
. When using random strings for protection or security, don't use any of them!!! Try one of these api's: random.org – Ron van der Heijden May 29 '13 at 11:33Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, 5);
– frieder Aug 15 '14 at 9:28[a-zA-Z0-9]
so why the[^a-z]
? Also, what about random uppercase letters? – ringø Feb 5 '15 at 7:47