This question already has an answer here:
What's the shortest way (within reason) to generate a random alpha-numeric (uppercase, lowercase, and numbers) string in JavaScript to use as a probably-unique identifier?
This question already has an answer here:
What's the shortest way (within reason) to generate a random alpha-numeric (uppercase, lowercase, and numbers) string in JavaScript to use as a probably-unique identifier?
This function should give a random string in any length.
I've tested it with the following test that succeeded.
The reason i have chosen 25 is since that in practice the length of the string returned from
Math.random().toString(36).substr(2, 25)
has length 25. This number can be changed as you wish.This function is recursive and hence calling the function with very large values can result with
Maximum call stack size exceeded
. From my testing i was able to get string in the length of 300,000 characters.This function can be converted to a tail recursion by sending the string to the function as a second parameter. I'm not sure if JS uses Tail call optimization
When I saw this question I thought of when I had to generate UUIDs. I can't take credit for the code, as I am sure I found it here on stackoverflow. If you dont want the dashes in your string then take out the dashes. Here is the function:
Fiddle: http://jsfiddle.net/nlviands/fNPvf/11227/
Summary:
Some explanation:
[...Array(len)]
Array(len) or new Array(len) creates an array with undefined pointer(s). One-liners are going to be harder to pull off. The Spread syntax conveniently defines the pointers (now they point to undefined objects!).
.reduce(
Reduce the array to, in this case, a single string. The reduce functionality is common in most languages and worth learning.
a=>a+...
We're using an arrow function.
a
is the accumulator. In this case it's the end-result string we're going to return when we're done (you know it's a string because the second argument to the reduce function, the initialValue is an empty string:''
). So basically: convert each element in the array withp[~~(Math.random()*p.length)]
, append the result to thea
string and give mea
when you're done.p[...]
p
is the string of characters we're selecting from. You can access chars in a string like an index (E.g.,"abcdefg"[3]
gives us"d"
)~~(Math.random()*p.length)
Math.random()
returns a floating point between [0, 1)Math.floor(Math.random()*max)
is the de facto standard for getting a random integer in javascript.~
is the bitwise NOT operator in javascript.~~
is a shorter, arguably sometimes faster, and definitely funner way to sayMath.floor(
Here's some infoUsing lodash: