Skip to content

Instantly share code, notes, and snippets.

@ArtemAvramenko
Last active January 23, 2024 09:25
Show Gist options
  • Save ArtemAvramenko/bf4aae42d7ab58ef0531e066feed7795 to your computer and use it in GitHub Desktop.
Save ArtemAvramenko/bf4aae42d7ab58ef0531e066feed7795 to your computer and use it in GitHub Desktop.
Ignoring whitespaces in Javascript RegExp patterns
/**
* ignores comments and whitespaces in regexp patterns,
* similar to RegexOptions.IgnorePatternWhitespace in C#
* or Pattern.COMMENTS in Java.
* @example
* // returns /[a-z][0-9]+/i
* new RegExp(ignoreWhitespaces`
* [a-z] # any latin letter
* [0-9]+ # any number
* `, 'i');
*/
export function ignoreWhitespaces(/** @type TemplateStringsArray */ pattern, /** @type string[] */ ...expr) {
let raw = '';
for (let i = 0; i < pattern.raw.length; i++) {
raw += pattern.raw[i];
if (i < expr.length) {
raw += expr[i]; // allow dynamic patterns, e.g. `a${'b'}c`
}
}
let result = '';
for (let line of raw.split('\n')) {
const commentIndex = line.search(/(?<!\\)#/); // skip comments, but allow escaping with \
if (commentIndex >= 0) {
line = line.substring(0, commentIndex);
}
result += line.trim();
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment