Home > Web Front-end > JS Tutorial > javascript creates random string containing numbers and letters

javascript creates random string containing numbers and letters

高洛峰
Release: 2017-01-14 10:29:41
Original
1189 people have browsed it

First type:

//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;
}
Copy after login

Second type: No need to enter character set

function randomstring(L){
  var s= &#39;&#39;;
  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))
Copy after login

Third type: Support custom character length and characteristic character set

function randomString(len, charSet) {
  charSet = charSet || &#39;ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789&#39;;
  var randomString = &#39;&#39;;
  for (var i = 0; i < len; i++) {
   var randomPoz = Math.floor(Math.random() * charSet.length);
   randomString += charSet.substring(randomPoz,randomPoz+1);
  }
  return randomString;
}
Copy after login

Call with default charset [a-zA-Z0-9] or send in your own:

var randomValue = randomString(5);
 
var randomValue = randomString(5, &#39;PICKCHARSFROMTHISSET&#39;);
Copy after login

Demo screenshot

javascript creates random string containing numbers and letters

The above is a summary of the three methods of creating random strings containing numbers and letters in JavaScript. You can refer to them if you need them.

For more articles related to javascript creating random strings containing numbers and letters, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template