xxxxxxxxxx
const randStr = (length, min, max) => String.fromCharCode(Array(length).fill().map(() => Math.floor(Math.random() * (max - min + 1)) + min))
console.log(randStr(10, 65, 90));
console.log(randStr(10, 97, 122)) //output: "jxqjxqjxqj")); between lowercase a
// z (10 letters)
function randStr(n) {
var str = '';
for (var i = 0; i < n; i++) {
str += String.fromCharCode(Math.floor(Math.random() * 26) + 97);
}
return str;
}
xxxxxxxxxx
// this one is quite compact and generates 11 random letters+numbers
Math.random().toString(36).substring(2) // random output like "0r4q9s1how7"
// just change substring() from 2 to 11 to reduce the string
xxxxxxxxxx
Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
xxxxxxxxxx
// Create a function for reusable perpose
const generateRandomString = (myLength) => {
const chars =
"AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz1234567890";
const randomArray = Array.from(
{ length: myLength },
(v, k) => chars[Math.floor(Math.random() * chars.length)]
);
const randomString = randomArray.join("");
return randomString;
};
// Try it
console.log(generateRandomString(10));
console.log(generateRandomString(30));
xxxxxxxxxx
<?php
declare(strict_types=1);
function randomStrGenerator(int $length): string
{
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
if ($length < 5) {
return 'inputed value must be greater than 4';
} else {
for ($i = 0; $i < $length; $i++) {
$index = rand(0, strlen($characters) - 1);
$randomString .= $characters[$index];
}
return $randomString;
}
}
echo "Error : ".randomStrGenerator(4)."\n"; //This will throw an error with what the function expects
echo "Length of 5: ".randomStrGenerator(5)."\n"; // This will give us a random length of 5 strings
echo "Length of 10: ".randomStrGenerator(10)."\n";//This will give us a random length of 10 strings
echo "Length of 20: ".randomStrGenerator(20)."\n";//This will give us a random length of 20 strings
echo "Hope you find this helpful";
xxxxxxxxxx
//Can change 7 to 2 for longer results.
let randomString = (Math.random() + 1).toString(36).substring(6);
Create a random string 6-characters long.
xxxxxxxxxx
#include <random>
#include <string>
std::string random_string()
{
std::string str("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
std::random_device rd;
std::mt19937 generator(rd());
std::shuffle(str.begin(), str.end(), generator);
return str.substr(0, 32); // assumes 32 < number of characters in str
}
xxxxxxxxxx
import random
import string
def generate_random_string(length):
letters = string.ascii_letters + string.digits + string.punctuation
return ''.join(random.choice(letters) for _ in range(length))
# Usage example: Generate a random string of length 10
random_string = generate_random_string(10)
print(random_string)