Socket
Socket
Sign inDemoInstall

better-randstr

Package Overview
Dependencies
0
Maintainers
1
Versions
2
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    better-randstr

Fully-customizable random string generator


Version published
Weekly downloads
4
increased by100%
Maintainers
1
Install size
25.5 kB
Created
Weekly downloads
 

Readme

Source

better-randstr

npm (tag) Build Status License

🌞 Fully-customizable random string generator. Useful for testing applications, etc.

  • Works with browsers, NodeJS and DenoJS (JavaScript 6+ and TypeScript)
  • No external dependencies
  • Unit-tested
  • Semantic Versioning
  • It can be used with your preferred pseudo-random generator (PRNG).

Install

npm i better-randstr

Declaration

Browser

Global:

<script crossorigin src="https://unpkg.com/better-randstr" >
<script>console.log( randstr() );</script>

ESM:

<script type="module" >
import { randstr } from 'https://unpkg.com/better-randstr/index.esm.js';
console.log( randstr() );
</script>

NodeJS

const { randstr } = require('better-randstr');
console.log( randstr() );

Deno

import { randstr } from 'https://unpkg.com/better-randstr/index.esm.js';
console.log( randstr() );

Usage Examples

// Default:
// - Up to 100 characters
// - No control characters
// - ASCII + ISO (UTF-8)
randstr();
// => ;Þë?Ç¡m{îU4I0_%L*qV

// Using a customized function as random function, instead of Math.random()
const myRandomFunc = /* a function that returns a number between 0 and 1 */ ;
randstr( { random: myRandomFunc } );
// => cy¦¼Óé6Lcy

// Exactly 10 characters
randstr( { length: 10 } );
// => »²y+iÀëC#Ù

// At least 10 characters
randstr( { length: [ 10 ] } );
// => ü¢ ß~å¿Û¿\ÓÜtÈ["ª9¡.:`i¡{ã«?®Q=>?v&ëÿ2"Âë

// At most 10 characters
randstr( { length: [ 0, 10 ] } );
// => ȹt×úÓ¯ÖÃj

// Between 2 and 60 characters
randstr( { length: [ 2, 60 ] } );
// => ZÔý­ÛÏaæ»û_Eâo9¨§­:Çu!ÕÄø|FNߨj)1n¦Í:

// Exactly 10 characters, with only the specified characters
randstr( { length: 10, chars: 'ABC123' } );
// => A31AAB3AB1

// Exactly 10 characters, only characters in the range, no control characters
randstr( { length: 10, chars: [ 32, 127 ] } ); // ASCII range
// => EA*bY7{*cL

// Exactly 10 characters, between 'A' and 'Z'
randstr( { length: 10, chars: [ 'A'.charCodeAt( 0 ), 'Z'.charCodeAt( 0 ) ] } );
// => SPQJNORXXR

// Exactly 10 characters, only numbers
const { NUMBERS } = require( 'better-randstr' );
randstr( { length: 10, chars: NUMBERS } ) // same as passing '0123456789'
// => 7450625283

// Exactly 10 characters, alfanumeric
const { ALPHA_NUMERIC } = require( 'better-randstr' );
randstr( { length: 10, chars: ALPHA_NUMERIC } );
// => s1wMa7QVmg

// Exactly 10 characters, all characters in ASCII/ISO (UTF-8) except the specified
randstr( { length: 10, acceptable: function( chr ) {
    return '%#&$'.indexOf( chr ) < 0; // acceptable if not found
} } );
// => ´NvÄ~]¿Gº]

// Exactly 10 characters, escaping quotes and single-quotes
randstr( { length: 10, replacer: function( chr ) {
    switch ( chr ) {
        case '"': return '\\"';
        case "'": return "\\'";
    }
    return chr;
} } );
// => ñ;}éÔÝf«\'

// Include control characters
randstr( { includeControlChars: true } );
// => x@HA$÷°Gݳ:^Ê%¼˜¤®ý±”#ShŠ+Ò+Å|

// Wider range than UTF-8 - control characters not avoided!
randstr( { chars: [ 32, 1000 ] } );
// => r΅4ƹǭ̻ɍĿΠsɊQȍάĠIJȤċƳȭɧĄƹĜʋ͏Ʒȥĭ˟͢"Ȓǭ̼Ζ˂̀ƖǛ̚3&΃ƏϧȷɥŃ

See example.js

API

function randstr( options: Options ): string;

where Options is :

{

    /**
     * Random function to be used. By default, it assumes `Math.random()`.
     *
     * The function does not expect arguments and must return a number between 0 and 1.
     */
    random?: function () => number;

    /**
     * Length or length range. By default, it assumes `[ 0, 100 ]`.
     *
     * - Number: Minimum and maximum length will be equal to the provided number. Example: `{ length: 20 }`.
     * - One-length array: Maximum will be a random number greater than or equal to the minimum. Example: `{ length: [ 2 ] }`.
     * - Two-length array: Minimum and maximum length will assume the provided numbers. Example: `{ length: [ 0, 50 ] }`.
     */
    length?: number | number[];

    /**
     * Allowed characters or byte range. By default, it assumes `[32, 255]`
     * which is a range containing the first printable ASCII character (`32`)
     * and the last ISO character (`255`).
     *
     * For example, `"0123456789"`, which gives the same result as
     * `['0'.charCodeAt(0), '9'.charCodeAt(0)]`.
     */
    chars?: string | number[];

    /**
     * Function that evaluates whether the generated character is acceptable.
     * By default, it is `undefined`.
     * The function expects a character and returns a boolean.
     */
    acceptable?: function ( string ) => boolean;

    /**
     * Function that replaces a character by other character or characters.
     * By default, it is `undefined`.
     * You may use it for escaping or replacing certain characters, for example.
     */
    replacer?: function ( string ) => string;

    /**
     * Whether is desired to include control characters. By default, it is `false`.
     */
    includeControlChars?: boolean;
}

See also

License

MIT © Thiago Delgado Pinto

Keywords

FAQs

Last updated on 03 Jan 2022

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc