How to make random string to use for random password or id in Javascript?

So easily to do that, you just write a function below and use it in anywhere:

Call function is makeRandomString

function makeRandomString(length) {
  let text = "";
  const possible =
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  for (let i = 0; i < length; i++)
    text += possible.charAt(Math.floor(Math.random() * possible.length));
  return text;
}
Copy this code


Usage:

To use, you just call this function and pass a parameter inside, this parameter is the length of output string that you want.

 const myRandomPassWord = makeRandomString(14);
// Result will be like this: hzxUNlrYV9WGc1
Copy this code


Demo: