Created
August 7, 2024 17:25
-
-
Save dacarley/b5d0ce434d68ca90b928b2c90f1c40c3 to your computer and use it in GitHub Desktop.
A tagged template string implementation for composing regexes
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
import { isRegExp, zipWith } from 'lodash'; | |
export function regex(strings: TemplateStringsArray, ...values: any[]): RegExp { | |
const pattern = zipWith(strings, values, (str, value) => { | |
if (isRegExp(value)) { | |
value = value.source.replace(/^\^|\$$/g, ''); | |
} | |
return str + (value ?? ''); | |
}).join(''); | |
return new RegExp(pattern); | |
} | |
const MIME_TYPE = /^[a-zA-Z]+\/[a-zA-Z]+$/; | |
/** | |
* Matches the beginning of a base64 string | |
* | |
* For performance reasons, this regex is not exhaustive. It only validates the beginning of the string. | |
* | |
* A prior version of this regex attempted to validate the entire string, but it had terrible peformance, and could cause out-of-memory errors. | |
*/ | |
const BASE64_STRING = /^[A-Za-z\d+/_-]{1,100}/; | |
/** | |
* Matches the beginning of a well-formed, base64-encoded data url | |
* | |
* For performance reasons, this regex is not exhaustive. It only validates the beginning of the string. | |
* | |
* A prior version of this regex attempted to validate the entire string, but it had terrible peformance, and could cause out-of-memory errors. | |
*/ | |
const DATA_URL = regex`^data:${MIME_TYPE};base64,${BASE64_STRING}`; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment