Skip to content

@kaelyx/ts-kit / string / randomString

Function: randomString() ​

randomString(options?): string

Defined in: string/random-string/random-string.ts:31

Makes a random string from a set of characters. It uses crypto.getRandomValues and has no modulo bias, so the result is safe to use for tokens and passwords.

Parameters ​

options? ​

RandomStringOptions

Optional. See RandomStringOptions.

Returns ​

string

A string of length characters. A length of 0 gives ''.

Throws ​

If length is not an integer of 0 or more, or if charset is empty.

Example ​

ts
randomString() // 'f3Kq9ZbT0xLmA2pR'
randomString({ length: 8, charset: RandomStringCharset.hex }) // '9c4e01ab'
randomString({ charset: RandomStringCharset.uppercase + RandomStringCharset.digits }) // 'Q7ZK2M9XA0B4TR1C'
randomString({ length: 6, charset: 'ab' }) // 'babbab'
randomString({ length: 0 }) // ''
randomString({ length: -1 }) // throws RangeError
randomString({ charset: '' }) // throws RangeError

Types ​

RandomStringOptions interface ​

Defined in: string/random-string/random-string.types.ts:32

Options for randomString.

Properties ​

charset? ​

readonly optional charset?: string

Defined in: string/random-string/random-string.types.ts:39

The characters to pick from. Duplicate characters are ignored, so each character has the same chance.

Default ​
ts
RandomStringCharset.alphanumeric

length? ​

readonly optional length?: number

Defined in: string/random-string/random-string.types.ts:34

The number of characters in the result. Must be an integer of 0 or more.

Default ​
ts
16