Created
May 28, 2019 14:38
-
-
Save blackmjck/c38e4c581098e0a3b432125598987cc5 to your computer and use it in GitHub Desktop.
Regular Expressions via easy concatenation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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