Skip to content

Generate random string with only numbers or alphabet in JavaScript

This is a simple approach to generate random string with either numbers or letters using a predefined set.

function generateRandomString(alphabetsOnly, numbersOnly, n) {
  var text = "";
  var possible = alphabetsOnly?"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz":"" + numbersOnly?"0123456789":"";

  for (var i = 0; i < n; i++)
    text += possible.charAt(Math.floor(Math.random() * possible.length));

  return text;
}

generateRandomString(true, false, 6) //ZmyQnw
generateRandomString(true, true, 6) //FUCcCl
generateRandomString(false, true, 6) //165785
See also  Find the number of days between two days using JavaScript

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.