Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate random string with Angular 6 [duplicate]

Is there a way to generate a random String with 40 random symbols using typescript?

like image 850
Peter Penzov Avatar asked Sep 26 '26 12:09

Peter Penzov


2 Answers

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);
like image 77
smtaha512 Avatar answered Sep 28 '26 02:09

smtaha512


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);
like image 33
Sergey Mell Avatar answered Sep 28 '26 01:09

Sergey Mell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!