Skip to main content

Generate a random string from given characters

JavaScript version

const generateString = (length, chars) =>
Array(length)
.fill('')
.map((v) => chars[Math.floor(Math.random() * chars.length)])
.join('');

TypeScript version

const generateString = (length: number, chars: string) =>
Array(length)
.fill('')
.map((v) => chars[Math.floor(Math.random() * chars.length)])
.join('');

Examples

generateString(10, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');

Comments