Home>

If i want to create a string containing numbers, letters (case), or symbols,For example, create a random string from the [a-za-z0-9] set,The length is 5. Is there any better code?This article provides several methods,Includes automatic character set changes.Let ’s learn together.

The first:

//code from http://caibaojian.com/js-random-string.html
function makeid ()
{
  var text="";
  var possible="abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789";
  for (var i=0;i<5;i ++)
    text +=possible.charat (math.floor (math.random () * possible.length));
  return text;
}

The second type:no need to enter a character set

function randomstring (l) {
  var s="";
  var randomchar=function () {
   var n=math.floor (math.random () * 62);
   if (n<10) return n;//1-10
   if (n<36) return string.fromcharcode (n + 55);//a-z
   return string.fromcharcode (n + 61);//a-z
  }
  while (s.length<l) s +=randomchar ();
  return s;
}

alert (randomstring (5))

The third type:support custom character length and characteristic character set

function randomstring (len, charset) {
  charset=charset || "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789";
  var randomstring="";
  for (var i=0;i<len;i ++) {
   var randompoz=math.floor (math.random () * charset.length);
   randomstring +=charset.substring (randompoz, randompoz + 1);
  }
  return randomstring;
}

call with default charset [a-za-z0-9] or send in your own:

var randomvalue=randomstring (5);
var randomvalue=randomstring (5, "pickcharsfromthisset");

Demo screenshot

  • Previous Log4j different modules output to different files
  • Next AngularJS basic ng-include directive simple example