Random alpha-numeric string in JavaScript?
If you only want to allow specific characters, you could also do it like this:
function randomString(length, chars) {
var result = '';
for (var i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)];
return result;
}
var rString = randomString(32, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');
Here's a jsfiddle to demonstrate: http://jsfiddle.net/wSQBx/
Another way to do it could be to use a special string that tells the function what types of characters to use. You could do that like this:
function randomString(length, chars) {
var mask = '';
if (chars.indexOf('a') > -1) mask += 'abcdefghijklmnopqrstuvwxyz';
if (chars.indexOf('A') > -1) mask += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
if (chars.indexOf('#') > -1) mask += '0123456789';
if (chars.indexOf('!') > -1) mask += '~`!@#$%^&*()_+-={}[]:";\'<>?,./|\\';
var result = '';
for (var i = length; i > 0; --i) result += mask[Math.floor(Math.random() * mask.length)];
return result;
}
console.log(randomString(16, 'aA'));
console.log(randomString(32, '#aA'));
console.log(randomString(64, '#A!'));
Fiddle: http://jsfiddle.net/wSQBx/2/
Alternatively, to use the base36 method as described below you could do something like this:
function randomString(length) {
return Math.round((Math.pow(36, length + 1) - Math.random() * Math.pow(36, length))).toString(36).slice(1);
}
Generate random string/characters in JavaScript
I think this will work for you:
function makeid(length) {
let result = '';
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
const charactersLength = characters.length;
let counter = 0;
while (counter < length) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
counter += 1;
}
return result;
}
console.log(makeid(5));
Generate unique random alphanumeric using javascript
Here's something that would return only unique alphanumerics
function alphanumeric_unique() {
return Math.random().toString(36).split('').filter( function(value, index, self) {
return self.indexOf(value) === index;
}).join('').substr(2,8);
}
FIDDLE
Splitting the string into an array of characters, then using Array.filter()
to filter out any characters that are already in the array to get only one instance of each character, and then finally joining the characters back to a string, and running substr(2, 8)
to get the same length string as in the question, where it starts at the second character and gets a total of eight characters.
How to generate a unique alphanumeric string with atleast a number?
The OR ||
will return true if one of both conditions is true, so if there is no number it will pass the if clause.
You could check if both conditions are true instead:
if ($number && $uppercase) {
// do something with $values
}
Running this again $func();
inside the if clause, will run the function again generating a new string and returns $randomString;
from the function.
If you want to return the tested string, you can return the already tested $values
EDIT
If you don't want to return only chars A-Z or only digits, you can update the pattern to match only digit or only chars A-Z using ^\d+$
and ^[A-Z]+$
If one if the conditions is true, then do a recursive call.
protected function generate(int $length = 4): string
{
$randomString = '';
$characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
for ($i = 0; $i < $length; $i++) {
$index = random_int(0, strlen($characters) - 1);
$randomString .= $characters[$index];
}
$uppercase = preg_match('@^[A-Z]+$@', $randomString);
$number = preg_match('@^\d+$@', $randomString);
if ($uppercase || $number) {
$randomString = $this->generate();
}
return $randomString;
}
See a PHP demo.
Javascript Random Alphanumeric Generator, Specific Format
String.fromCharCode()
will give you a capital letter if you enter numbers from 65 to 90. So if you use this function 3 times with 3 random numbers between (and including) 65-90 you can generate three random capital letters:
const getRandomLetters = function(count) { let acc = ''; // the resulting string (to return once results appended) for(let i = 0; i < count; i++) { // generate amount const randomCharCode = Math.floor(Math.random() * (91 - 65)) + 65; acc += String.fromCharCode(randomCharCode); } return acc;}
const characters = getRandomLetters(3);console.log(characters);
Generate alphanumeric string that starts with not numeric character
What you can do is generate the first letter separatly from the rest of the string.
This can be done by taking a random letter from a string for example.
Exemple
const CHARACTERS='abcdefghijklmnopqrstuvwxyz'
const makeRandomString = (len) => {
const letter = CHARACTERS[Math.floor(Math.random()*CHARACTERS.length)];
return letter + [...Array(len - 1)].map(() => Math.random().toString(36)[2]).join("");
};
console.log(makeRandomString(10))
Generate random string/characters in JavaScript
I think this will work for you:
function makeid(length) {
let result = '';
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
const charactersLength = characters.length;
let counter = 0;
while (counter < length) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
counter += 1;
}
return result;
}
console.log(makeid(5));
Related Topics
Var Name Produces Strange Result in JavaScript
What Does ${} (Dollar Sign and Curly Braces) Mean in a String in JavaScript
Proper Use of Const for Defining Functions
Npm Install Cannot Find Module 'Semver'
Boolean Variable Returns as String from JavaScript Function
Watch Multiple $Scope Attributes
Fastest Way to Check a String Contain Another Substring in JavaScript
How to Upload a File Using Jquery.Ajax and Formdata
Sort Objects in an Array Alphabetically on One Property of the Array
Mobile Safari: JavaScript Focus() Method on Inputfield Only Works with Click
Jquery .On() Method with Multiple Event Handlers to One Selector
What Does Arrow Function '() => {}' Mean in JavaScript
Scaling Socket.Io to Multiple Node.Js Processes Using Cluster