Created
July 23, 2013 13:36
-
-
Save 6174/6062387 to your computer and use it in GitHub Desktop.
Generate a random string in JavaScript In a short and fast way!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript | |
Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15); |
const idString = async (string_length) => {
var random_str = "";
var characters =
"ABCDEFGHIJKLMNOPQRSTUVWXYZqeytrpolkadjsghfgmnbzxcvnQPOWEYRKASJHDGFMNBCVX--___-_jsfhrlg-_124903564576986483658fgh4sdfh687e4h897WETHJ68F7G4688471877GFHJFFGJ87469857468746hfghwrtiyj4598yhdjkhgnk";
for (let index = 0; index < string_length; index++) {
random_str += characters.charAt(
Math.floor(Math.random() * characters.length)
);
}
let string = `${random_str}`;
console.log(string);
return string;
};
@zeelkakdiya constructive feedback to improve this code:
- This is not an async function, it does not use promises
- var is used rather than
let
and in some casesconst
are more appropriate let string
does not need${}
- console.log is not useful in production code and actually slows down this function
- let string to return could be removed.
- casing is inconsistent
const generateID = (stringLength = 20) => {
let randomStr = "";
const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZqeytrpolkadjsghfgmnbzxcvnQPOWEYRKASJHDGFMNBCVX--___-_jsfhrlg-_124903564576986483658fgh4sdfh687e4h897WETHJ68F7G4688471877GFHJFFGJ87469857468746hfghwrtiyj4598yhdjkhgnk";
for (let index = 0; index < stringLength; index++) {
randomStr += characters.charAt(
Math.floor(Math.random() * characters.length)
);
}
return randomStr;
};
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Using recursion with the option of providing a prefix.