JS Basics-generating random strings of letters and numbers by JS

Source: Internet
Author: User
Tags alphanumeric characters

In your project, you may want to randomly generate alphanumeric characters, such as 3-32 a random string ( 位数不固定 ) that generates a bit-length alphanumeric combination 43 , or generate a 位数固定 bit-random string ( )

Using the combination of the Math.random () and the ToString () method

First look at this way:

Math.random (). toString (36);

Results:0.9kfiead48n
toStringAfter the argument can be any integer between 2-36, the default is 10 (that is, decimal), the return value is that random number.

    • If even, the returned numeric string is short, and if it is odd, the returned value will be a large representation of the length.
    • If <10 It is a number, >10 it will contain letters.

So if you want to get a long list of random characters, you need to use a > 10 and an odd number of arguments. But because the decimal point is returned, it needs to be intercepted slice(2) and can be used. Here's substr() how to use it. As follows:

Math.random (). toString (+). substr (2);

Results:p3bz2xrzsam

But the above method is just random, the number of digits is uncertain. How to control the number of bits in a range or fixed? Look at the following method.

General function notation
/** Randomly generate a fixed number of digits or a range of string number combinations * @param {#} min range min * @param {number} max range maximum, when not passed, represents a combination of generating the specified digits * @returns {String} Returns the string result **/functionrandomrange (min, max) {varReturnstr = "", Range= (max? Math.Round (Math.random () * (max-min)) +min:min), arr= [' 0 ', ' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 ', ' A ', ' B ', ' C ', ' d ', ' e ', ' f ', ' g ', ' h ', ' I ', ' j ', ' K ', ' l ', ' m ', ' n ', ' O ', ' P ', ' Q ', ' R ', ' s ', ' t ', ' u ', ' V ', ' w ', ' x ', ' y ', ' z ', ' A ', ' B ', ' C ', ' D ', ' E ', ' F ', ' G ', ' H ', ' I ', ' J ', ' K ', ' L ', ' M ', ' N ', ' O ', ' P ', ' Q ', ' R ', ' S ', ' T ', ' U ', ' V ', ' W ', ' X ', ' Y ', ' Z '];  for(vari=0; i<range; i++){        varindex = Math.Round (Math.random () * (arr.length-1)); Returnstr+=Arr[index]; }    returnreturnstr;}varRAND01 = Randomrange (10,22);varRAND02 = Randomrange (10,36);varRAND03 = Randomrange (10);varRAND04 = Randomrange (10);

Results:

vkdwqniokntspuouuntgjrhvl7umc9jlvyjur1f1ck8i7yvsepgpzuo5f
Optimization of function wording

Think of the above arr is too cumbersome to write, can also be written as a string form, the implementation of the way is almost just a little bit changed:

functionrandomrange (min, max) {varReturnstr = "", Range= (max? Math.Round (Math.random () * (max-min)) +min:min), Charstr= ' ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 ';  for(vari=0; i<range; i++){        varindex = Math.Round (Math.random () * (charstr.length-1)); Returnstr+ = Charstr.substring (index,index+1); }    returnreturnstr;}varRAND01 = Randomrange (10,22);varRAND02 = Randomrange (10,36);varRAND03 = Randomrange (10);varRAND04 = Randomrange (10);

Results:

Jpjtfe4s7aosuaiguywkn1mr5bdnf4jrbfmj6habh7fzlkbbhnw8v4y
Extension: Generating a combination from a specified string
/** Randomly generate a fixed number of digits or a range of string number combinations * @param {#} min range Minimum * @param {number} max range maximum, when not passed represents a combination of generating a specified amount of digits * @param {String} c HARSTR the specified string in the generated combination * @returns {string} returns a string result **/functionrandomrange (min, max, charstr) {varReturnstr = "", Range; if(typeofMax = = ' String ') {Charstr=Max; } Range= ((Max &&typeofmax = = ' number ')? Math.Round (Math.random () * (max-min)) +min:min); Charstr= Charstr | | ' ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 ';  for(vari=0; i<range; i++){        varindex = Math.Round (Math.random () * (charstr.length-1)); Returnstr+ = Charstr.substring (index,index+1); }    returnreturnstr;}varRAND01 = Randomrange (10,22);varRAND02 = Randomrange (5,8, ' abcdef012 ');varRAND03 = Randomrange (10);varRAND04 = Randomrange (5, ' 123 ');

Results:

la2vvo4jrxzlhvlbs8b5k1bc0cd1ae888oluqx32232
Further optimizations, which do not pass parameters, generate a string combination of the specified number of bits by default
/** Randomly generate a fixed number of digits or a range of string number combinations * @param {#} min range Minimum * @param {number} max range maximum, when not passed represents a combination of generating a specified amount of digits * @param {String} c HARSTR the specified string in the generated combination * @returns {string} returns a string result **/functionrandomrange (min, max, charstr) {varReturnstr = "", Range; if(typeofMin = = ' undefined ') {min= 10; }     if(typeofMax = = ' String ') {Charstr=Max; } Range= ((Max &&typeofmax = = ' number ')? Math.Round (Math.random () * (max-min)) +min:min); Charstr= Charstr | | ' ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 ';  for(vari=0; i<range; i++){        varindex = Math.Round (Math.random () * (charstr.length-1)); Returnstr+ = Charstr.substring (index,index+1); }    returnreturnstr;}varRAND01 = Randomrange ();

Results:

Ohcjkcltul
In optimization, generate combinations based on ASCII code

by printing:

// 0-9ascii Range: 48-57console.log (' a '. charCodeAt (0)); // a-zascii Range: 97-122console.log (' a '. charCodeAt (0)); // a-zascii Range: 65-90

ASCII code corresponding to common characters

    • a-z 97-122
    • A-Z 65-90
    • 0-9 45-57

In charStr fact, we don't have to write that long string when we know this.

/** Randomly generate a fixed number of digits or a range of string number combinations * @param {#} min range Minimum * @param {number} max range maximum, when not passed represents a combination of generating a specified amount of digits * @param {String} c HARSTR the specified string in the generated combination * @returns {string} returns a string result **/functionrandomrange (min, max, charstr) {varReturnstr = "",//the returned stringRange//the resulting string length            //randomly generated characters    varAutogetstr =function(){        varCharfun =function(){            varN= Math.floor (Math.random () *62); if(n<10){                returnN//1-10            }            Else if(n<36){                returnString.fromCharCode (n+55);//A- z            }            Else{                returnString.fromCharCode (n+61);//A- z            }        }         while(returnstr.length<range) {Returnstr+=Charfun ();        }    }; //generates a combination based on the specified string    varAccordcharstrget =function(){         for(vari=0; i<range; i++){            varindex = Math.Round (Math.random () * (charstr.length-1)); Returnstr+ = Charstr.substring (index,index+1);    }    }; if(typeofMin = = ' undefined ') {min= 10; }     if(typeofMax = = ' String ') {Charstr=Max; } Range= ((Max &&typeofmax = = ' number ')? Math.Round (Math.random () * (max-min)) +min:min); if(CHARSTR) {accordcharstrget (); }Else{autogetstr (); }    returnreturnstr;}varRAND01 =Randomrange ();varRAND02 = Randomrange (5,8, ' abcdef012 ');varRAND03 = Randomrange (10);varRAND04 = Randomrange (5, ' 123 ');

Results:

s0yiespj4qdff0dzx93g07ewd22232
Reference address
    • Https://www.cnblogs.com/makan/p/4850071.html

JS Basics-generating random strings of letters and numbers by JS

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.