Token generator

Generate random string with the chars you want, uppercase or lowercase letters, numbers and/or symbols.

1const textUppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
2const textLowercase = 'abcdefghijklmnopqrstuvwxyz'
3const textNumber = '1234567890'
4const textSymbol = '!@#$%^&*()_+-=[]{}|;:,.<>/?'
5
6type GenerateRandomTokenOptions = {
7  isUppercase: boolean
8  isLowercase: boolean
9  isNumber: boolean
10  isSymbol: boolean
11  length: number
12}
13
14export const generateRandomToken = (
15  options: GenerateRandomTokenOptions,
16): string => {
17  const { isLowercase, isNumber, isSymbol, isUppercase, length } = options
18  let token = ''
19  token += isUppercase ? textUppercase : ''
20  token += isLowercase ? textLowercase : ''
21  token += isNumber ? textNumber : ''
22  token += isSymbol ? textSymbol : ''
23
24  if (token === '') {
25    return ''
26  }
27
28  const times = Math.ceil(length / token.length)
29  token = token.repeat(times)
30  token = shuffleString(token)
31  token = token.slice(0, length)
32
33  return token
34}
35
1const shuffleString = (text: string) => {
2  const array = text.split('')
3  for (let i = 0; i < array.length; i++) {
4    const j = Math.floor(Math.random() * (array.length - 1))
5    const temp = array[i]
6    array[i] = array[j]
7    array[j] = temp
8  }
9  return array.join('')
10}
11