js randomly generates 26 upper and lower case letters

  • 2020-12-20 03:27:53
  • OfStack

js generates 26 upper and lower case letters, using str.charCodeAt () and String.fromCharCode () methods

1. Use charCodeAt() to get the Unicode encoding for a specific character in a string.
fromCharCode() accepts one (or more) of the specified Unicode values and returns the corresponding string.


// Generate capital letters  A the Unicode A value of 65
function generateBig_1(){
 var str = [];
 for(var i=65;i<91;i++){
  str.push(String.fromCharCode(i));
 }
 return str;
}
// Generate capital letters  a the Unicode A value of 97
function generateSmall_1(){
 var str = [];
 for(var i=97;i<123;i++){
  str.push(String.fromCharCode(i));
 }
 return str;
}
// Converts a string to Unicode code 
function toUnicode(str){
 var codes = [];
 for(var i=0;i<str.length;i++){
  codes.push(str.charCodeAt(i));
 }
 return codes;
}
 
function generateSmall(){
 var ch_small = 'a';
 var str_small = '';
 for(var i=0;i<26;i++){
  str_small += String.fromCharCode(ch_small.charCodeAt(0)+i);
 }
 return str_small;
}
 
function generateBig(){
 var ch_big = 'A';
 var str_big = '';
 for(var i=0;i<26;i++){
  str_big += String.fromCharCode(ch_big.charCodeAt(0)+i);
 }
 return str_big;
}
 
console.log(generateBig());
console.log(generateSmall());
 
console.log(toUnicode(generateBig()));
console.log(toUnicode(generateSmall()));
 
console.log(generateBig_1());
console.log(generateSmall_1());

Here's how js randomly generates 26 upper and lower case letters with key lines of code:


function getCharacter(flag){ 
 var character=""; 
 if(flag==="lower"){ 
 character = String.fromCharCode(Math.floor(Math.random()*26)+"a".charCodeAt(0)); 
 } 
 if(flag==="upper"){ 
 character = String.fromCharCode(Math.floor(Math.random()*26)+"A".charCodeAt(0)); 
 } 
 return character; 
} 
function getUpperCharacter(){ 
 return getCharacter("upper");; 
}
function getLowerCharacter(){ 
 return getCharacter("lower");; 
} 
console.log(getUpperCharacter());
console.log(getLowerCharacter());

Above code to achieve our requirements, can randomly output capital letters or small letters, the principle is very simple, is the use of capital letters or lower case Unicode code interval to achieve.

Code 2:


/** 
*  return 1 Random lowercase letters  
*/ 
function getLowerCharacter(){ 
return getCharacter("lower");; 
} 


/** 
*  return 1 Random capital letters  
*/ 
function getUpperCharacter(){ 
return getCharacter("upper");; 
} 


/** 
*  return 1 A letter  
*/ 
function getCharacter(flag){ 
var character = ""; 
if(flag === "lower"){ 
character = String.fromCharCode(Math.floor( Math.random() * 26) + "a".charCodeAt(0)); 
} 
if(flag === "upper"){ 
character = String.fromCharCode(Math.floor( Math.random() * 26) + "A".charCodeAt(0)); 
} 
return character; 
} 

This article mainly introduces how to use javascript to output random uppercase or lowercase letters, hoping to give you more or less help.


Related articles: