How to print 5 random alphanumeric strings on one click in Javascript? - javascript

I am able to create single alphanumeric string at a time by clicking on a button by using Math.random() function.
But i need to print 5 alphanumeric random values at a time by clicking on button.
Please help me out I am beginner in javascript and got stuck.
I really need some solution for that

This works by generating random numbers in base 10 then converting them to base 36, where digits include both numbers and letters (10 digits + 26 letters = 36).
'use strict';
document.querySelector('button').onclick = function () {
const strings = new Array(5)
.fill()
.map(() => Math.random() * 10000)
.map((n) => n.toString(36).replace(/\./, ''));
console.log(strings);
}
<button>Click</button>

This works: Generating random number with Math.random between 65 and 100 (ASCII: A-Z and 10 more for the digits) and useString.fromCharCode to convert it to char. For getting the number subtratct the differnce in ASCII if the random is greater 90. Use a for-loop and add the chars.
document.getElementById('btn').addEventListener('click', () => {
let random = '';
for (let x = 0; x < 5; x++) {
let randInt = Math.floor((Math.random() * 35) + 65);
random += String.fromCharCode((randInt<=90) ? randInt : randInt-43);
}
document.getElementById('random').textContent=random;
});
<button id='btn'>Random</button>
<div id='random'></div>

Related

How do I generate random bulk tracking numbers?

how to generate multiple tracking numbers, and also how to make them like this.
UB5775XXXXXHK
So "XXXXX" above will be scrambled and become multiple tracking numbers like this
UB577594624HK
UB577573536HK
UB577593735HK
and so on until the number of limits we want
Use Math.random() * 10 to generate a random float
Use Math.floor() or the quicker ~~ to floor the result (remove decimals)
Concatenate your digits using +=
Insert them where needed using Template Literals (or again using concatenation +)
const trackingNumber = (pr = "UB775", su = "HK") => {
for(let i=0; i<5; i++) pr += ~~(Math.random() * 10);
return pr + su;
};
console.log(trackingNumber());
console.log(trackingNumber());
console.log(trackingNumber());
console.log(trackingNumber());
// Example changing prefix and suffix:
console.log(trackingNumber("ZA001", "PD"));
You can do something like this:
const input = "UB5775XXXXXHK";
const randomNumber = () => Math.trunc(Math.random() * 10); // To genrate a random number
const genrateTrackingNum = (str) => str.replace(/X/g, randomNumber); // To replace X with a random number
console.log(genrateTrackingNum(input));
console.log(genrateTrackingNum(input));
console.log(genrateTrackingNum(input));
console.log(genrateTrackingNum(input));
console.log(genrateTrackingNum(input));
▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬
Explanation:
The randomNumber function will generate a random number from 0 to 9.
const randomNumber = () => Math.trunc(Math.random() * 10);
The genrateTrackingNum function will replace every X in the input string (here UB5775XXXXXHK) with a random number.
const genrateTrackingNum = (str) => str.replace(/X/g, randomNumber);

How to Generate a random number of fixed length using JavaScript?

I'm trying to generate a random number that must have a fixed length of exactly 6 digits.
I don't know if JavaScript has given below would ever create a number less than 6 digits?
Math.floor((Math.random()*1000000)+1);
I found this question and answer on StackOverflow here. But, it's unclear.
EDIT: I ran the above code a bunch of times, and Yes, it frequently creates numbers less than 6 digits. Is there a quick/fast way to make sure it's always exactly 6 digits?
console.log(Math.floor(100000 + Math.random() * 900000));
Will always create a number of 6 digits and it ensures the first digit will never be 0. The code in your question will create a number of less than 6 digits.
Only fully reliable answer that offers full randomness, without loss. The other ones prior to this answer all looses out depending on how many characters you want. The more you want, the more they lose randomness.
They achieve it by limiting the amount of numbers possible preceding the fixed length.
So for instance, a random number of fixed length 2 would be 10 - 99. For 3, 100 - 999. For 4, 1000 - 9999. For 5 10000 - 99999 and so on. As can be seen by the pattern, it suggests 10% loss of randomness because numbers prior to that are not possible. Why?
For really large numbers ( 18, 24, 48 ) 10% is still a lot of numbers to loose out on.
function generate(n) {
var add = 1, max = 12 - add; // 12 is the min safe number Math.random() can generate without it starting to pad the end with zeros.
if ( n > max ) {
return generate(max) + generate(n - max);
}
max = Math.pow(10, n+add);
var min = max/10; // Math.pow(10, n) basically
var number = Math.floor( Math.random() * (max - min + 1) ) + min;
return ("" + number).substring(add);
}
The generator allows for ~infinite length without lossy precision and with minimal performance cost.
Example:
generate(2)
"03"
generate(2)
"72"
generate(2)
"20"
generate(3)
"301"
generate(3)
"436"
generate(3)
"015"
As you can see, even the zero are included initially which is an additional 10% loss just that, besides the fact that numbers prior to 10^n are not possible.
That is now a total of 20%.
Also, the other options have an upper limit on how many characters you can actually generate.
Example with cost:
var start = new Date(); var num = generate(1000); console.log('Time: ', new Date() - start, 'ms for', num)
Logs:
Time: 0 ms for 7884381040581542028523049580942716270617684062141718855897876833390671831652069714762698108211737288889182869856548142946579393971303478191296939612816492205372814129483213770914444439430297923875275475120712223308258993696422444618241506074080831777597175223850085606310877065533844577763231043780302367695330451000357920496047212646138908106805663879875404784849990477942580056343258756712280958474020627842245866908290819748829427029211991533809630060693336825924167793796369987750553539230834216505824880709596544701685608502486365633618424746636614437646240783649056696052311741095247677377387232206206230001648953246132624571185908487227730250573902216708727944082363775298758556612347564746106354407311558683595834088577220946790036272364740219788470832285646664462382109714500242379237782088931632873392735450875490295512846026376692233811845787949465417190308589695423418373731970944293954443996348633968914665773009376928939207861596826457540403314327582156399232931348229798533882278769760
More hardcore:
generate(100000).length === 100000 -> true
I would go with this solution:
Math.floor(Math.random() * 899999 + 100000)
More generally, generating a random integer with fixed length can be done using Math.pow:
var randomFixedInteger = function (length) {
return Math.floor(Math.pow(10, length-1) + Math.random() * (Math.pow(10, length) - Math.pow(10, length-1) - 1));
}
To answer the question: randomFixedInteger(6);
You can use the below code to generate a random number that will always be 6 digits:
Math.random().toString().substr(2, 6)
Hope this works for everyone :)
Briefly how this works is Math.random() generates a random number between 0 and 1 which we convert to a string and using .toString() and take a 6 digit sample from said string using .substr() with the parameters 2, 6 to start the sample from the 2nd char and continue it for 6 characters.
This can be used for any length number.
If you want to do more reading on this here are some links to the docs to save you some googling:
Math.random(): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
.toString(): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString
.substr(): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr
short with arbitrary precision
below code ALWAYS generate string with n digits - solution in snippet use it
[...Array(n)].map(_=>Math.random()*10|0).join``
let gen = n=> [...Array(n)].map(_=>Math.random()*10|0).join``
// TEST: generate 6 digit number
// first number can't be zero - so we generate it separatley
let sixDigitStr = (1+Math.random()*9|0) + gen(5)
console.log( +(sixDigitStr) ) // + convert to num
100000 + Math.floor(Math.random() * 900000);
will give a number from 100000 to 999999 (inclusive).
Based on link you've provided, right answer should be
Math.floor(Math.random()*899999+100000);
Math.random() returns float between 0 and 1, so minimum number will be 100000, max - 999999. Exactly 6 digits, as you wanted :)
Here is my function I use. n - string length you want to generate
function generateRandomNumber(n) {
return Math.floor(Math.random() * (9 * Math.pow(10, n - 1))) + Math.pow(10, n - 1);
}
This is another random number generator that i use often, it also prevent the first digit from been zero(0)
function randomNumber(length) {
var text = "";
var possible = "123456789";
for (var i = 0; i < length; i++) {
var sup = Math.floor(Math.random() * possible.length);
text += i > 0 && sup == i ? "0" : possible.charAt(sup);
}
return Number(text);
}
let length = 6;
("0".repeat(length) + Math.floor(Math.random() * 10 ** length)).slice(-length);
Math.random() - Returns floating point number between 0 - 1
10 ** length - Multiply it by the length so we can get 1 - 6 length numbers with decimals
Math.floor() - Returns above number to integer(Largest integer to the given number).
What if we get less than 6 digits number?
That's why you have to append 0s with it.
"0".repeat() repeats the given string which is 0
So we may get more than 6 digits right?
That's why we have to use "".slice() method. It returns the array within given indexes. By giving minus values, it counts from the last element.
I created the below function to generate random number of fix length:
function getRandomNum(length) {
var randomNum =
(Math.pow(10,length).toString().slice(length-1) +
Math.floor((Math.random()*Math.pow(10,length))+1).toString()).slice(-length);
return randomNum;
}
This will basically add 0's at the beginning to make the length of the number as required.
npm install --save randomatic
var randomize = require('randomatic');
randomize(pattern, length, options);
Example:
To generate a 10-character randomized string using all available characters:
randomize('*', 10);
//=> 'x2_^-5_T[$'
randomize('Aa0!', 10);
//=> 'LV3u~BSGhw'
a: Lowercase alpha characters (abcdefghijklmnopqrstuvwxyz'
A: Uppercase alpha characters (ABCDEFGHIJKLMNOPQRSTUVWXYZ')
0: Numeric characters (0123456789')
!: Special characters (~!##$%^&()_+-={}[];\',.)
*: All characters (all of the above combined)
?: Custom characters (pass a string of custom characters to the options)
NPM repo
I use randojs to make the randomness simpler and more readable. you can pick a random int between 100000 and 999999 like this with randojs:
console.log(rando(100000, 999999));
<script src="https://randojs.com/1.0.0.js"></script>
const generate = n => String(Math.ceil(Math.random() * 10**n)).padStart(n, '0')
// n being the length of the random number.
Use a parseInt() or Number() on the result if you want an integer.
If you don't want the first integer to be a 0 then you could use padEnd() instead of padStart().
I was thinking about the same today and then go with the solution.
var generateOTP = function(otpLength=6) {
let baseNumber = Math.pow(10, otpLength -1 );
let number = Math.floor(Math.random()*baseNumber);
/*
Check if number have 0 as first digit
*/
if (number < baseNumber) {
number += baseNumber;
}
return number;
};
Let me know if it has any bug. Thanks.
"To Generate Random Number Using JS"
console.log(
Math.floor(Math.random() * 1000000)
);
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Math.random()</h2>
<p id="demo"></p>
</body>
</html>
You can use this module https://www.npmjs.com/package/uid, it generates variable length unique id
uid(10) => "hbswt489ts"
uid() => "rhvtfnt" Defaults to 7
Or you can have a look at this module https://www.npmjs.com/package/shortid
const shortid = require('shortid');
console.log(shortid.generate());
// PPBqWA9
Hope it works for you :)
var number = Math.floor(Math.random() * 9000000000) + 1000000000;
console.log(number);
This can be simplest way and reliable one.
For the length of 6, recursiveness doesn't matter a lot.
function random(len) {
let result = Math.floor(Math.random() * Math.pow(10, len));
return (result.toString().length < len) ? random(len) : result;
}
console.log(random(6));
In case you also want the first digit to be able to be 0 this is my solution:
const getRange = (size, start = 0) => Array(size).fill(0).map((_, i) => i + start);
const getRandomDigit = () => Math.floor(Math.random() * 10);
const generateVerificationCode = () => getRange(6).map(getRandomDigit).join('');
console.log(generateVerificationCode())
generate a random number that must have a fixed length of exactly 6 digits:
("000000"+Math.floor((Math.random()*1000000)+1)).slice(-6)
Generate a random number that will be 6 digits:
console.log(Math.floor(Math.random() * 900000));
Result = 500229
Generate a random number that will be 4 digits:
console.log(Math.floor(Math.random() * 9000));
Result = 8751
This code provides nearly full randomness:
function generator() {
const ran = () => [1, 2, 3, 4, 5, 6, 7, 8, 9, 0].sort((x, z) => {
ren = Math.random();
if (ren == 0.5) return 0;
return ren > 0.5 ? 1 : -1
})
return Array(6).fill(null).map(x => ran()[(Math.random() * 9).toFixed()]).join('')
}
console.log(generator())
This code provides complete randomness:
function generator() {
const ran1 = () => [1, 2, 3, 4, 5, 6, 7, 8, 9, 0].sort((x, z) => {
ren = Math.random();
if (ren == 0.5) return 0;
return ren > 0.5 ? 1 : -1
})
const ran2 = () => ran1().sort((x, z) => {
ren = Math.random();
if (ren == 0.5) return 0;
return ren > 0.5 ? 1 : -1
})
return Array(6).fill(null).map(x => ran2()[(Math.random() * 9).toFixed()]).join('')
}
console.log(generator())
parseInt(Math.random().toString().slice(2,Math.min(length+2, 18)), 10); // 18 -> due to max digits in Math.random
Update:
This method has few flaws:
- Sometimes the number of digits might be lesser if its left padded with zeroes.

generate random number using specific digits in javascript

In my program I want to generate 5 digit random number such the that contain only digits ( 1 to 7).
var randnum = Math.floor(Math.random() * (11111 - 77777 + 1)) + 11111;
Using above code I got number between 11111 and 77777. But how to generate the number that does not contain 0,8,9 ? Is there any default method to generate this kind of numbers?
You can generate each digit at a time, concatenate them then parseInt to get your result:
var str = '';
for (var i=0; i<5; i++) {
str += Math.floor(Math.random()*7) + 1;
}
var randnum = parseInt(str);
Demo
Explanation
Math.random() returns [0,1)
Math.random() * 7 returns [0,7)
Math.floor(...) returns 0,1,2,3,4,5,6
...+1 returns 1,2,3,4,5,6,7
For example,
digits = [1,2,3,4,5,6,7]
len = 5
num = 0
while(len--)
num = num * 10 + digits[Math.floor(Math.random() * digits.length)]
console.log(num)
This way you can easily select which digits to use.

get the number of n digit in a 2+ digit number

For example, getting "5" in "256". The closest I've gotten is Math.floor(256/10)), but that'll still return the numbers in front. Is there any simple way to get what I want or would I have to make a big function for it? Also, for clarity: "n digit" would be defined. Example, getDigit(2,256) would return 5 (second digit)
Math.floor((256 / 10) % 10)
or more generally:
Math.floor(N / (Math.pow(10, n)) % 10)
where N is the number to be extracted, and n is the position of the digit. Note that this counts from 0 starting from the right (i.e., the least significant digit = 0), and doesn't account for invalid values of n.
how about
(12345 + "")[3]
or
(12345 + "").charAt(3)
to count from the other end
[length of string - digit you want] so if you want the 2 it's:
5 - 4 = 1
(12345 + "")[1] = "2"
function getNumber (var num, var pos){
var sNum = num + "";
if(pos > sNum.length || pos <= 0){return "";}
return sNum[sNum.length - pos];
}
First, you need to cast the number to a string, then you can access the character as normal:
var num = 256;
var char = num.toString()[1]; // get the 2nd (0-based index) character from the stringified version of num
Edit: Note also that, if you want to access it without setting the number as a variable first, you need a double dot .. to access the function:
var char = 256..toString()[1];
The first dot tells the interpreter "this is a number"; the second accesses the function.
Convert to string and substring(2,2)?
This should do it:
function getDigit ( position, number ) {
number = number + ""; // convert number to string
return number.substr ( position + 1, 1 ); // I'm adding 1 to position, since 0 is the position of the first character and so on
}
Try this, last line is key:
var number = 12345;
var n = 2;
var nDigit = parseInt((number + '').substr(1,1));
If you want to try to do everything mathematically:
var number = 256;
var digitNum = 2;
var digit = ((int)(number/(Math.pow(10,digitNum-1))%10;
This code counts the digit from the right starting with 1, not 0. If you wish to change it to start at 0, delete the -1 portion in the call.
If you wish to count from the left, it gets more complicated and similar to other solutions:
var number = 256;
var digitNum = 2;
var digit = ((int)(number/(Math.pow(10,number.tostring().length-digitNum))%10;
edit:
Also, this assumes you want base 10 for your number system, but both of those will work with other bases. All you need to do is change instances of 10 in the final line of code to the number representing the base for the number system you'd like to use. (ie. hexadecimal =16, binary = 2)
// You do not say if you allow decimal fractions or negative numbers-
// the strings of those need adjusting.
Number.prototype.nthDigit= function(n){
var s= String(this).replace(/\D+/g,'');
if(s.length<=n) return null;
return Number(s.charAt(n))
}
use variable "count" to control loop
var count = 1; //starting 1
for(i=0; i<100; i++){
console.log(count);
if(i%10 == 0) count++;
}
output will fill
1
2
3
4
5
6
7
8
9

JavaScript, Generate a Random Number that is 9 numbers in length

I'm looking for an efficient, elegant way to generate a JavaScript variable that is 9 digits in length:
Example: 323760488
You could generate 9 random digits and concatenate them all together.
Or, you could call random() and multiply the result by 1000000000:
Math.floor(Math.random() * 1000000000);
Since Math.random() generates a random double precision number between 0 and 1, you will have enough digits of precision to still have randomness in your least significant place.
If you want to ensure that your number starts with a nonzero digit, try:
Math.floor(100000000 + Math.random() * 900000000);
Or pad with zeros:
function LeftPadWithZeros(number, length)
{
var str = '' + number;
while (str.length < length) {
str = '0' + str;
}
return str;
}
Or pad using this inline 'trick'.
why don't just extract digits from the Math.random() string representation?
Math.random().toString().slice(2,11);
/*
Math.random() -> 0.12345678901234
.toString() -> "0.12345678901234"
.slice(2,11) -> "123456789"
*/
(requirement is that every javascript implementation Math.random()'s precision is at least 9 decimal places)
Also...
function getRandom(length) {
return Math.floor(Math.pow(10, length-1) + Math.random() * 9 * Math.pow(10, length-1));
}
getRandom(9) => 234664534
Three methods I've found in order of efficiency:
(Test machine running Firefox 7.0 Win XP)
parseInt(Math.random()*1000000000, 10)
1 million iterations: ~626ms. By far the fastest - parseInt is a native function vs calling the Math library again. NOTE: See below.
Math.floor(Math.random()*1000000000)
1 million iterations: ~1005ms. Two function calls.
String(Math.random()).substring(2,11)
1 million iterations: ~2997ms. Three function calls.
And also...
parseInt(Math.random()*1000000000)
1 million iterations: ~362ms.
NOTE: parseInt is usually noted as unsafe to use without radix parameter. See https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/parseInt or google "JavaScript: The Good Parts". However, it seems the parameter passed to parseInt will never begin with '0' or '0x' since the input is first multiplied by 1000000000. YMMV.
Math.random().toFixed(length).split('.')[1]
Using toFixed alows you to set the length longer than the default (seems to generate 15-16 digits after the decimal. ToFixed will let you get more digits if you need them.
In one line(ish):
var len = 10;
parseInt((Math.random() * 9 + 1) * Math.pow(10,len-1), 10);
Steps:
We generate a random number that fulfil 1 ≤ x < 10.
Then, we multiply by Math.pow(10,len-1) (number with a length len).
Finally, parseInt() to remove decimals.
Thought I would take a stab at your question. When I ran the following code it worked for me.
<script type="text/javascript">
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
} //The maximum is exclusive and the minimum is inclusive
$(document).ready(function() {
$("#random-button").on("click", function() {
var randomNumber = getRandomInt(100000000, 999999999);
$("#random-number").html(randomNumber);
});
</script>
Does this already have enough answers?
I guess not. So, this should reliably provide a number with 9 digits, even if Math.random() decides to return something like 0.000235436:
Math.floor((Math.random() + Math.floor(Math.random()*9)+1) * Math.pow(10, 8))
Screen scrape this page:
9 random numbers
function rand(len){var x='';
for(var i=0;i<len;i++){x+=Math.floor(Math.random() * 10);}
return x;
}
rand(9);
If you mean to generate random telephone number, then they usually are forbidden to start with zero.
That is why you should combine few methods:
Math.floor(Math.random()*8+1)+Math.random().toString().slice(2,10);
this will generate random in between 100 000 000 to 999 999 999
With other methods I had a little trouble to get reliable results as leading zeroes was somehow a problem.
I know the answer is old, but I want to share this way to generate integers or float numbers from 0 to n. Note that the position of the point (float case) is random between the boundaries. The number is an string because the limitation of the MAX_SAFE_INTEGER that is now 9007199254740991
Math.hRandom = function(positions, float = false) {
var number = "";
var point = -1;
if (float) point = Math.floor(Math.random() * positions) + 1;
for (let i = 0; i < positions; i++) {
if (i == point) number += ".";
number += Math.floor(Math.random() * 10);
}
return number;
}
//integer random number 9 numbers
console.log(Math.hRandom(9));
//float random number from 0 to 9e1000 with 1000 numbers.
console.log(Math.hRandom(1000, true));
function randomCod(){
let code = "";
let chars = 'abcdefghijlmnopqrstuvxwz';
let numbers = '0123456789';
let specialCaracter = '/{}$%&#*/()!-=?<>';
for(let i = 4; i > 1; i--){
let random = Math.floor(Math.random() * 99999).toString();
code += specialCaracter[random.substring(i, i-1)] + ((parseInt(random.substring(i, i-1)) % 2 == 0) ? (chars[random.substring(i, i-1)].toUpperCase()) : (chars[random.substring(i, i+1)])) + (numbers[random.substring(i, i-1)]);
}
code = (code.indexOf("undefined") > -1 || code.indexOf("NaN") > -1) ? randomCod() : code;
return code;
}
With max exclusive: Math.floor(Math.random() * max);
With max inclusive: Math.round(Math.random() * max);
To generate a number string with length n, thanks to #nvitaterna, I came up with this:
1 + Math.floor(Math.random() * 9) + Math.random().toFixed(n - 1).split('.')[1]
It prevents first digit to be zero.
It can generate string with length ~ 50 each time you call it.
var number = Math.floor(Math.random() * 900000000) + 100000000
var number = Math.floor(Math.random()*899999999 + 100000000)
For a number of 10 characters
Math.floor(Math.random() * 9000000000) + 1000000000
From https://gist.github.com/lpf23/9762508
This answer is intended for people who are looking to generate a 10 digit number (without a country code)

Categories

Resources