Skip to content

Instantly share code, notes, and snippets.

@chrisseto
Last active March 9, 2016 22:04
Show Gist options
  • Save chrisseto/583ec623d287072c4003 to your computer and use it in GitHub Desktop.
Save chrisseto/583ec623d287072c4003 to your computer and use it in GitHub Desktop.
Given two bounding number generate a regex that matches that range, inclusive.
function regexRange(lo, hi) {
let re = [];
hi = hi.toString();
lo = lo.toString();
while (hi.length > lo.length) {
re.push(hi.split('').reduce((acc, c) => acc + `[${acc.length === 0 ? 1 : 0}-${c}]`, ''));
hi = '9'.repeat(hi.length - 1);
}
let i = 0;
re.push(lo.split('').reduce((acc, c) => acc + `[${c}-${hi[i++]||c}]`, ''));
return `(?:${re.map(s => `(?:${s})`).join('|')})`;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment