Closed jadjoubran closed 6 years ago
Thanks @mayankjain34 The problem with this one is that you can't specify how many random characters you want.. Do you know if there's a way to specify how many random characters you want? (of course while keeping it as simple as possible)
@jadjoubran if this is the case then this can be the answer.
function getRandomString(length) {
let string = '';
for(let i=0;i<length; i++) {
string += getChar();
}
return string;
}
function getChar() {
/***
ASCII code for
numbers [48-57]
alphabets [65-90, 97-122]
***/
let max = 123;
let min = 48;
let num = Math.floor(Math.random() * (max - min)) + min
if(num < 48 || (num > 57 && num < 65) || (num > 90 && num < 97) || (num > 122)) {
return getChar();
}
return String.fromCharCode(num);
}
console.log(getRandomString(20))
yeah, the problem however is that this is quite big to be included on codetogo I'll do some further research soon!
How about this:
const length = 7;
const charIndex = 5; // value should be kept between 2 and 8
const randomString = [...Array(length)].map(
() => Math.random().toString(36)[charIndex]
).join('') //generates "dblixbz"
The string generated by Math.random().toString(36)
is something like this 0.p0hrpf1chg
, the length of the string is around 10-12. That's the reason for keeping charIndex between 2 and 8.
This outputs a random text/sting of size length
everytime:
This is super cool @kakadiadarpan Will add the use case soon!
I will also add that this should not be used for cryptography
This can be the answer.
Math.random().toString(36).substr(2);