Related
I am trying to convert a string into mathematical expression, so I can calculate the value, but when I use the parseInt method it returns NAN:
function cal() {
const data = '(2 * 3 + 2) * (2 / 2)';
const info = data.replace(/\s/g, '');
const output = parseInt(info, 10);
console.log(output);
}
cal();
See Javascript eval()
function cal() {
const data = eval('(2 * 3 + 2) * (2 / 2)');
const output = parseInt(data, 10);
console.log(output);
}
cal();
You can use eval
Example :
const data = '(2 * 3 + 2) * (2 / 2)';
const result = eval(data)
console.log(result)
let str = 'asdwazsgdsadf' + 'qetgsadfdf';
let str2 = `asdqwedd qrqwee
fqfqw
qrwrq`;
let v1 = 100;
let v2 = 200;
let v3 = v1 * v2;
let str3 = `\${v1} * \${v2} = \${v3}`;
let t1 = 'hong'
console.log('v1 : ', `${v1}`); // out = v1 :
console.log('t1 : ', `${t1}`); // out = t1 :
console.log('str2 : ', str2);
console.log('str3 : ', str3); // out = str3 : 100 * 200 = 20000
this is my template literal test code.
other people can use ${v1} but my code is look like null.
what's matter of this code?
Without knowing more I'd say that you should check your environment to be sure that it can run template literals.
Check this list: CanIUse
with
`${v1} * ${v2} = ${v3}`
you should get the console log:
"100 * 200 = 20000"
but, whenever u add that backslash it takes away the speciality of the immediate special character followed by it , in your case, ($)
How to generate a random string containing only hex characters (0123456789abcdef) of a given length?
Short alternative using spread operator and .map()
Demo 1
const genRanHex = size => [...Array(size)].map(() => Math.floor(Math.random() * 16).toString(16)).join('');
console.log(genRanHex(6));
console.log(genRanHex(12));
console.log(genRanHex(3));
Pass in a number (size) for the length of the returned string.
Define an empty array (result) and an array of strings in the range of [0-9] and [a-f] (hexRef).
On each iteration of a for loop, generate a random number 0 to 15 and use it as the index of the value from the array of strings from step 2 (hexRef) -- then push() the value to the empty array from step 2 (result).
Return the array (result) as a join('')ed string.
Demo 2
const getRanHex = size => {
let result = [];
let hexRef = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
for (let n = 0; n < size; n++) {
result.push(hexRef[Math.floor(Math.random() * 16)]);
}
return result.join('');
}
console.log(getRanHex(6));
console.log(getRanHex(12));
console.log(getRanHex(3));
NodeJS Users
You can use randomBytes available in the crypto module, to generate cryptographically strong pseudorandom data of a given size. And you can easily convert it to hex.
import crypto from "crypto";
const randomString = crypto.randomBytes(8).toString("hex");
console.log(randomString) // ee48d32e6c724c4d
The above code snippet generates a random 8-bytes hex number, you can manipulate the length as you wish.
There are a few ways. One way is to just pull from a predefined string:
function genHexString(len) {
const hex = '0123456789ABCDEF';
let output = '';
for (let i = 0; i < len; ++i) {
output += hex.charAt(Math.floor(Math.random() * hex.length));
}
return output;
}
The other way is to append a random number between 0 and 15 converted to hex with toString:
function genHexString(len) {
let output = '';
for (let i = 0; i < len; ++i) {
output += (Math.floor(Math.random() * 16)).toString(16);
}
return output;
}
This securely generates a 32-byte random string and encodes it as hex (64 characters).
Array.from(crypto.getRandomValues(new Uint8Array(32)))
.map(b => b.toString(16).padStart(2, '0')).join('');
Long version:
function generateRandomHexString(numBytes) {
const bytes = crypto.getRandomValues(new Uint8Array(numBytes));
const array = Array.from(bytes);
const hexPairs = array.map(b => b.toString(16).padStart(2, '0'));
return hexPairs.join('')
}
If you can use lodash library here is the code snippet to generate a 16 chars string:
let randomString = _.times(16, () => (Math.random()*0xF<<0).toString(16)).join('');
You can use a hexa number 0xfffff to random a hex string
getHexaNumb() {
return Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")
}
Length of the array is the length of the random string.
const randomHex = Array.from({ length: 32 }, () => "0123456789ABCDEF".charAt(Math.floor(Math.random() * 16))).join('');
console.log(randomHex);
Here's a version that avoids building one digit at a time; it's probably only suitable for short lengths.
function genHexString(len) {
const str = Math.floor(Math.random() * Math.pow(16, len)).toString(16);
return "0".repeat(len - str.length) + str;
}
This works for lengths up to 13:
randomHex = length => (
'0'.repeat(length)
+ Math.floor((Math.random() * 16 ** length))
.toString(16)
).slice(-length);
console.log(randomHex(4));
console.log(randomHex(6));
console.log(randomHex(13));
console.log(randomHex(20));
Up to 7 characters may be quickly taken from one Math.random() call (A):
const halfBytesIn35 = 7 // = 3.5 bytes
const byte35 = Math.pow(16, halfBytesIn35)
const bytes35 = () => ((Math.random() * byte35) | 0).toString(16).padStart(halfBytesIn35,'0')
console.log('A: ' + bytes35())
const bytes65 = len => Math.floor(Math.random() * Math.pow(16, len*2)).toString(16).padStart(len,'0')
console.log('B: ' + bytes65(6))
function moreBytes (len) {
len *= 2; // alternative: len <<= 1 if you do not use half bytes. This might allow optimizations based on len always being an Integer then.
let builder = "";
while (len > 0) {
builder += bytes35()
len -= 7
}
return builder.slice(0,len)
}
console.log('C: ' + moreBytes(16))
Store the Math.pow constant if you plan to use this with high frequency.
An 8th letter overflows into the sign bit in the binary floor.
You can reach up to 13 characters from one call by using Math.floor instead (B) or even loop the generator for an arbitrary length (C).
Note that this could be used to define premature optimization. If your bottleneck really is the creation of Random Numbers consider using LUTs. This is common if you are developing for embedded. (And in this case somehow got stuck using javascript, but do not have the timebuget to generate random Numbers)
Using for Loop, charAt and Math.random
let result = "";
let hexChar = "0123456789abcdef";
for (var i = 0; i < 6; i++) {
result += hexChar.charAt(Math.floor(Math.random() * hexChar.length));
}
console.log(`#${result}`);
Using Math.random, you can do 13 characters at a time in a convenient way. If you want an arbitrary length string, you can still do it with a "one-liner":
const makeRandomHexString = (length: number) =>
Array.from({ length: Math.ceil(length / 13) })
.map(() =>
Math.floor(Math.random() * (Number.MAX_SAFE_INTEGER / 2))
.toString(16)
.padStart(13, '0')
)
.join('')
.substring(0, length);
Here is a simplified program to generate random hexadecimal Colour code:
let items = ["a", "b", "c", "d", "e", "f"];
let item = items[Math.floor(Math.random() * items.length)];
console.log(item);
let random = Math.random().toString().slice(2, 6);
console.log(`#${item}${random}${item}`);
let generateMacAdd = (function () {
let hexas = '0123456789ABCDEF'
let storeMac = []
let i = 0
do {
let random1st = hexas.charAt(Math.floor(Math.random() * hexas.length))
let random2nd = hexas.charAt(Math.floor(Math.random() * hexas.length))
storeMac.push(random1st + random2nd)
i++
} while (i <= 6)
return storeMac.join(':')
})()
console.log(generateMacAdd); //will generate a formatted mac address
I use self invoking function here so you can just call the variable
w/o any arguments
I also use do while here, just for my own convenience, you can do
any kind of loop depends what you're comfortable
function getTotal(){
var answers = ["A","K","Q","J", "10","9"]
var randomAnswer = answers[Math.floor(Math.random() * answers.length)];
const side1 = answers[Math.floor(Math.random() * answers.length)];
const side2 = answers[Math.floor(Math.random() * answers.length)];
const side3 = answers[Math.floor(Math.random() * answers.length)];
const side4 = answers[Math.floor(Math.random() * answers.length)];
const side5 = answers[Math.floor(Math.random() * answers.length)];
const diceTotal = side1 + side2 + side3 + side4 + side5;
console.log("diceTotal == " + diceTotal)
}
getTotal();
Above code is to get the random five numbers like say for assume 'AJK10Q',
Here into the array A - Ace ,K - King,Q-Queen,J - Jack,10, and 9.
How we can generate the different hand possibilities like
Five of a Kind,Full House ,Straight two pair etc..
it would be good if some one can idea or snippet on this ?
Thanks in Advance.
One easy way would be to have 4 of any numbers, then random through them, and pop the card, this way you won't get 5 As or 5 Ks for example.
let answers = ["A","K","Q","J", "10","9","A","K","Q","J", "10","9","A","K","Q","J", "10","9","A","K","Q","J", "10","9"]
let side = []
for (let i=1; i<=5; i++){
let x= Math.ceil(Math.random()*answers.length);
side.push(answers[x])
answers = [...answers.slice(0,3), ...answers.slice(4)]
}
console.log(side)
I am trying to execute below code:
var a = Math.floor(100000 + Math.random() * 900000);
a = a.substring(-2);
I am getting error like undefined is not a function at line 2, but when I try to do alert(a), it has something. What is wrong here?
That's because a is a number, not a string. What you probably want to do is something like this:
var val = Math.floor(1000 + Math.random() * 9000);
console.log(val);
Math.random() will generate a floating point number in the range [0, 1) (this is not a typo, it is standard mathematical notation to show that 1 is excluded from the range).
Multiplying by 9000 results in a range of [0, 9000).
Adding 1000 results in a range of [1000, 10000).
Flooring chops off the decimal value to give you an integer. Note that it does not round.
General Case
If you want to generate an integer in the range [x, y), you can use the following code:
Math.floor(x + (y - x) * Math.random());
This will generate 4-digit random number (0000-9999) using substring:
var seq = (Math.floor(Math.random() * 10000) + 10000).toString().substring(1);
console.log(seq);
I adapted Balajis to make it immutable and functional.
Because this doesn't use math you can use alphanumeric, emojis, very long pins etc
const getRandomPin = (chars, len)=>[...Array(len)].map(
(i)=>chars[Math.floor(Math.random()*chars.length)]
).join('');
//use it like this
getRandomPin('0123456789',4);
$( document ).ready(function() {
var a = Math.floor(100000 + Math.random() * 900000);
a = String(a);
a = a.substring(0,4);
alert( "valor:" +a );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
Your a is a number. To be able to use the substring function, it has to be a string first, try
var a = (Math.floor(100000 + Math.random() * 900000)).toString();
a = a.substring(-2);
You can get 4-digit this way .substring(startIndex, length), which would be in your case .substring(0, 4). To be able to use .substring() you will need to convert a to string by using .toString(). At the end, you can convert the resulting output into integer by using parseInt :
var a = Math.floor(100000 + Math.random() * 900000)
a = a.toString().substring(0, 4);
a = parseInt(a);
alert(a);
https://jsfiddle.net/v7dswkjf/
The problem is that a is a number. You cannot apply substring to a number so you have to convert the number to a string and then apply the function.
DEMO: https://jsfiddle.net/L0dba54m/
var a = Math.floor(100000 + Math.random() * 900000);
a = a.toString();
a = a.substring(-2);
$(document).ready(function() {
var a = Math.floor((Math.random() * 9999) + 999);
a = String(a);
a = a.substring(0, 4);
});
// It Will Generate Random 5 digit Number & Char
const char = '1234567890abcdefghijklmnopqrstuvwxyz'; //Random Generate Every Time From This Given Char
const length = 5;
let randomvalue = '';
for ( let i = 0; i < length; i++) {
const value = Math.floor(Math.random() * char.length);
randomvalue += char.substring(value, value + 1).toUpperCase();
}
console.log(randomvalue);
function getPin() {
let pin = Math.round(Math.random() * 10000);
let pinStr = pin + '';
// make sure that number is 4 digit
if (pinStr.length == 4) {
return pinStr;
} else {
return getPin();
}
}
let number = getPin();
Just pass Length of to number that need to be generated
await this.randomInteger(4);
async randomInteger(number) {
let length = parseInt(number);
let string:string = number.toString();
let min = 1* parseInt( string.padEnd(length,"0") ) ;
let max = parseInt( string.padEnd(length,"9") );
return Math.floor(
Math.random() * (max - min + 1) + min
)
}
I've created this function where you can defined the size of the OTP(One Time Password):
generateOtp = function (size) {
const zeros = '0'.repeat(size - 1);
const x = parseFloat('1' + zeros);
const y = parseFloat('9' + zeros);
const confirmationCode = String(Math.floor(x + Math.random() * y));
return confirmationCode;
}
How to use:
generateOtp(4)
generateOtp(5)
To avoid overflow, you can validate the size parameter to your case.
Numbers don't have substring method. For example:
let txt = "123456"; // Works, Cause that's a string.
let num = 123456; // Won't Work, Cause that's a number..
// let res = txt.substring(0, 3); // Works: 123
let res = num.substring(0, 3); // Throws Uncaught TypeError.
console.log(res); // Error
For Generating random 4 digit number, you can utilize Math.random()
For Example:
let randNum = (1000 + Math.random() * 9000).toFixed(0);
console.log(randNum);
This is quite simple
const arr = ["one", "Two", "Three"]
const randomNum = arr[Math.floor(Math.random() * arr.length)];
export const createOtp = (): number => {
Number(Math.floor(1000 + Math.random() * 9000).toString());
}