Generate random string containing numbers, uppercase, lowercase letters

I need to create a random string that contains numbers, uppercase and lowercase letters.

How should do it in JavaScript and PHP ?

What is the best way to generate it ?

What function should I use ?
0
give a positive ratinggive a negative rating
14 Apr 2023 at 07:14 PM
Hi,

To generate a random string that contains numbers, uppercase and lowercase letters, you have to use a bit more complex solution. You have to use your own function, because you can't get the result only by using a single statement. If you use md5() to generate the hash string, it will include numbers and only a few lowercase letters, because md5() uses a hexadecimal format.

The solutions bellow are based on array of characters, so you can modify it and keep there only the characters you would like to use. You can also add there a special characters if needed. The function is similar for Javascript or PHP. When calling the function, you have to specify how many characters should the string contain.

Generate random string in Javascript:

function randomString(l) {

let v = '';
const s = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
const a = s.length;
let c = 0;
for (let i = 0; i<l; i++) {
v += s.charAt(Math.floor(Math.random() * a));
c += 1;
}
return v;
}

Generate random string in PHP:

function randomString($l) {

$s = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
$a = strlen($s);
$v = "";
for ($i=0; $i<$l; $i++) {
$v .= $s[rand(0, $a-1)];
}
return $v;
}

1
give a positive ratinggive a negative rating
27 Apr 2023 at 11:54 AM
Tim
Share on FacebookShare on TwitterShare on LinkedInSend email
x
x
2024 AnswerTabsTermsContact us