Is there a way to generate a random String with 40 random symbols using typescript?
Asked
Active
Viewed 2.5k times
2 Answers
13
This is taken from a method written by one of our developers. May be this can help. I have modified it for you.
function makeRandom(lengthOfCode: number, possible: string) {
let text = "";
for (let i = 0; i < lengthOfCode; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
}
let possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890,./;'[]\=-)(*&^%$#@!~`";
const lengthOfCode = 40;
makeRandom(lengthOfCode, possible);

smtaha512
- 420
- 5
- 11
4
It's not about TypeScript actually, but JavaScript
You can use plenty of methods i.e.
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(40, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');
or
import some ready-to-use library like https://www.npmjs.com/package/randomstring and use it like
import randomString from 'randomstring';
const result = randomString.generate(40);

Sergey Mell
- 7,780
- 1
- 26
- 50