The stringGenerator
function is a simple and flexible utility that generates a random string based on specified character type options. You can control the length of the string and choose to include or exclude lowercase letters, uppercase letters, numbers, and symbols.
- Customizable Length: Specify the length of the generated string.
- Flexible Character Options: Choose to include or exclude lowercase letters, uppercase letters, numbers, and symbols.
- Default Settings: If no options are provided, the function will generate a string with all character types.
Using npm:
npm install @nakarmi23/random-string-generator
Using yarn:
yarn add @nakarmi23/random-string-generator
Using pnpm:
pnpm add @nakarmi23/random-string-generator
Once the package is installed, you can import the library using import
or require
approach:
import stringGenerator from '@nakarmi23/random-string-generator';
or
const {stringGenerator} = require('@nakarmi23/random-string-generator');
By default, the stringGenerator function generates a string of 20 characters, including lowercase letters, uppercase letters, numbers, and symbols.
const randomString = stringGenerator();
console.log(randomString); // Example output: 'aB3#cD4@eF5%gH6^'
You can customize the length of the string and specify which types of characters to include:
// Generate a string with 10 characters, including only uppercase letters and numbers.
const randomString = stringGenerator(10, { lowercase: false, symbol: false });
console.log(randomString); // Example output: 'A9B8C7D6E5'
If you disable all character options, the function will throw an error, as at least one option must be enabled:
try {
const randomString = stringGenerator(10, { lowercase: false, uppercase: false, number: false, symbol: false });
} catch (error) {
console.error(error.message); // Output: 'At least one option must be enabled'
}
Generates a random string based on the provided parameters.
- Parameter:
-
length
(number
, optional): The length of the generated string. Defaults to 20. -
options
(object
, optional): An object specifying which character types to include:-
lowercase
(boolean
, optional): Include lowercase letters (a-z). Defaults totrue
. -
uppercase
(boolean
, optional): Include uppercase letters (A-Z). Defaults totrue
. -
number
(boolean
, optional): Include numbers (0-9). Defaults totrue
. -
symbol
(boolean
, optional): Include symbols (e.g., @, #, $, etc.). Defaults totrue
.
-
- returns: A randomly generated string of the specified length and character types.
- throws: If all options are disabled, an error is thrown to indicate that at least one option must be enabled.
-