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);
Related
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>
The first time I type the random variable in the console I get a number between 1 and 10 which is expected. Then every time I retype the random variable it gives me the same number. Why is this?
var random = Math.floor(Math.random() * 10) + 1;
Instead of using a variable, you should create a function to generate a random number.
const random = () => Math.floor(Math.random() * 10) + 1;
const number1 = random();
const number2 = random();
const number3 = random();
console.log(number1, number2, number3);
Also this is useful,
const randomVariable = function () {
return Math.floor(Math.random() * 4);
};
randomVariable();
I write this line but get an error in response:
slice can't process there.
Why and how do I fix that?
function (row) {
var r = Math.round(Object.values(row)[3] / Object.values(row)[4]);
var t = Object.values(row)[2];
var s = Math.round((t - r) / t * 100);
return '<span id="up">${s.slice(0,2)}%</span>'
}
Your variable s is a number but the slice function requires a string. The solution would be to cast s into a string:
const slice = `${s}`.slice(0, 2);
Edit
To display a number with n decimals, you can multiply it by 10^n before rounding and then dividing it by the same number, cutting of anything after n decimals.
// display number with n decimals
const numberDisplay = (number, numberOfDecimals) => Math.round(number * Math.pow(10, numberOfDecimals)) / Math.pow(10, numberOfDecimals);
// your desired number display
const slice = numberDisplay(s, 2);
How can I add percent to a sum? I have tried var sum = 3.25 + '3.4%'; but it didn't work. I'm just getting 0.00 as an answer.
To "add a percent to a number" means "multiply the number by (1 + pct)":
var sum = 3.25;
sum = sum * (1 + 0.034);
You could equivalently skip the 1 (that's just the way I think about it) and add:
var sum = 3.25;
sum += sum * 0.034;
So if you're starting off with a string representation of a percentage, you can use parseFloat() to make it a number:
var pct = "3.4%"; // or from an <input> field or whatever
pct = parseFloat(pct) / 100;
The parseFloat() function conveniently ignores trailing non-numeric stuff like the "%" sign. Usually that's kind-of a problem, but in this case it saves the step of sanitizing the string.
The simplest method is to use arithmetic operators.
var sum = 3.25
sum += sum *= 0.034;
< 3.3605
String concatenation and number adding using the same + symbol. You need to use () around the numbers.
var sum = (3.25+3.4)+"%";
let's assume that you want to add x percent to the current number :
const percentage = 14.5; let number = 100 const numberPlusPercentage = number + number / 100 * percentage
console.log('result = 'numberPlusPercentage.toFixed(2))
result = 114.5
As the title says ... is it possible to create a random 16 digit number with jquery?
Just use:
Math.floor(Math.random()*1E16)
EDIT :
Note that there is about a 1/10 chance of a lower number of digits. If Math.random() generates something like 0.0942104924071337 then 0.0942104924071337 * 1E16 is 0942104924071337 which evaluates to 942104924071337; a 15 digit number.
The only way to 100% guarantee that the number is 16 digits in length is to have it be formed as a string. Using this method I would recommend #rjmunro's answer:
number = (Math.random()+' ').substring(2,10)+(Math.random()+' ').substring(2,10);
Not with jQuery, no, but you can do it with plain javascript.
If you want exactly 16 digits (possibly including leading 0s), I would start with Math.random(), convert to a string, pick 8 digits, and concatenate 2 runs together.
number = (Math.random() + '').substring(2,10)
+ (Math.random() + '').substring(2,10);
No, use JAVASCRIPT!
jQuery is not some magic genie.
This is a task which is much better suited for raw javascript. For example
var str = '';
var i;
for (i = 0; i < 16; i++) {
var number = Math.floor(Math.random() * 10) % 10;
str += number;
}
I just tried with #rjmunro 's answer.
Unfortunately, it does generate string less than 16digits,
but very rare, approxly once in 10 million times.
Here is my testing code, runs in nodejs:
'use strict';
var fs = require('fs');
var totalTimes = 100000000;
var times = totalTimes;
var fileName;
var writeStream;
while (times > 0) {
var key = (Math.random() + ' ').substring(2,10) + (Math.random() + ' ').substring(2,10);
times --;
if (key.length !== 16) {
var msg = 'a flaw key gened: ' + key + '\n';
// create a log file at first time
if (!fileName) {
fileName = 'log/flaw_key_' + new Date() + '.txt';
}
writeStream = fs.createWriteStream(fileName);
writeStream.write(msg);
writeStream.end();
}
if (times === 0) {
console.log(totalTimes + ' times key gened');
}
}
Also #Dimitri Mikadze 's answer generate less length string as well, so I eventually adopt a way with some concept of his solution:
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
/**
* Gen random digits string in specific length
* #param {Int} length of string
*
* #return {String}
*
*/
function genString(length) {
var times = length;
var key = '';
while (times > 0) {
times --;
key += getRandomInt(0, 9);
}
return key;
}
genString(16); // a 16 digits string
u can use this function to generate random digits, just pass minimum and maximum parameters
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
random 16 digit, usage
randomInt(0, 9999999999999999);
I know this question is old but this simple function will guarantee a 16 (or however many you want) character string every time without the 10% failure rate of other solutions. Can change it to a number if you need to.
function generate() {
let string = ""
while (string.length < 16) {
let number = Math.floor(Math.random() * 10).toString()
string += number
}
return string
}
I think this way is more beautiful:
const generateFixedLengthNumberInString = length =>
[...Array(length).keys()].reduce(
previousValue =>
previousValue + String(Math.floor(Math.random() * 10) % 10),
);
console.log(generateFixedLengthNumberInString(16))
// prints "0587139224228340"