generate a random string in typescript

To generate a random string in TypeScript, you can use the following function:

index.ts
function generateRandomString(length: number): string {
  let result = '';
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  const charactersLength = characters.length;
  for ( let i = 0; i < length; i++ ) {
     result += characters.charAt(Math.floor(Math.random() * charactersLength));
  }
  return result;
}
350 chars
10 lines

This function takes in a length parameter, which specifies the length of the random string you want to generate. The function then creates a string of possible characters to choose from (characters). It then loops length number of times, randomly selects a character from the characters string, and appends it to the result string. Finally, it returns the result string, which is the randomly generated string of the specified length.

You can call this function like this:

index.ts
const randomString = generateRandomString(10); // generates a random string of length 10
console.log(randomString); // outputs something like: "Kj39spf02D"
156 chars
3 lines

gistlibby LogSnag