Skip to content

Instantly share code, notes, and snippets.

@westc
Last active May 11, 2018 05:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save westc/99fb1be7f953f3aaf38c7dfd05191651 to your computer and use it in GitHub Desktop.
Save westc/99fb1be7f953f3aaf38c7dfd05191651 to your computer and use it in GitHub Desktop.
Random string generator for JS, JS (ES6), PHP, and Python.
<?php
function random_string($length, $opt_chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz") {
for ($l = strlen($opt_chars) - 1, $s = ""; $length--; ) {
$s .= substr($opt_chars, rand(0, $l), 1);
}
return $s;
}
import random
def random_string(length, opt_chars="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"):
return ''.join([random.choice(opt_chars) for i in range(length)])
function randomString(length, opt_chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz') {
return [...Array(length)].map(_ => opt_chars[~~(Math.random() * opt_chars.length)]).join('');
}
function randomString(length, opt_chars) {
opt_chars = opt_chars || '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
for (var l = opt_chars.length, s = ''; length--; ) {
s += opt_chars.charAt(~~(Math.random() * opt_chars.length));
}
return s;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment