Skip to content

Instantly share code, notes, and snippets.

@blackmjck
Created May 28, 2019 14:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save blackmjck/c38e4c581098e0a3b432125598987cc5 to your computer and use it in GitHub Desktop.
Save blackmjck/c38e4c581098e0a3b432125598987cc5 to your computer and use it in GitHub Desktop.
Regular Expressions via easy concatenation
/**
* For convenience's sake (and to avoid all those '\\\' strings), this can be used to create new regular expression objects
* from any strings or existing RegExp objects input via simple concatenation.
* @param {string[]|RegExp[]} args - any number of strings or regular expressions
* @param {string} [flags] - optional flags
* @returns {RegExp}
*/
function compileRegExp( args, flags = '' ) {
const src = args.map( arg => {
if ( arg instanceof RegExp ) return arg.source;
if ( typeof arg === 'string' ) return arg;
throw new TypeError( 'Provided arguments must be of type String or RegExp' );
} ).join( '' );
return new RegExp( src, flags );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment