Skip to content

randomString() Helper Method

The randomString() Helper Method module provides a helper function that generates a random continuous string.

Import

To import the randomString() Helper Method:

javascript
import { randomString } from '@obewds/vueventus'

Arguments

Returns: String

ArgsTypeStatusDescription
lengthNumberOptionalDesired length of the output randomized string characters, where no argument will return a default value of a 10 character long randomized string

Use Example

javascript
console.log( randomString() )
// returns 10 character long random (string)

console.log( randomString(5) )
// returns 5 character long random (string)

console.log( randomString(35) )
// returns 35 character long random (string)

Module Code

ts
// ./src/helpers/randomString.ts
// https://stackoverflow.com/questions/1349404/generate-random-string-characters-in-javascript

export default function (length = 10): string {
    let result = '';
    const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    const charactersLength = characters.length;
    for ( let i = 0; i < Number(length); i++ ) {
      result += characters.charAt( Math.floor(Math.random() * charactersLength) );
   }
   return result;
}

Released under the MIT License