A function that extracts the set of possible first consumed characters from a regular expression.
If any character or no character could be matched, or if over 1000 different characters could be matched, or if the library is not quite sure (e.g. when using unicode property escapes or references), null is returned instead.
All features up to ES2025 are supported.
npm install regexp-get-prefiximport getPrefix from 'regexp-get-prefix';
// Let's extract the set of possible first consumed characters
getPrefix ( /foo|bar/ ); // => Set { 'f', 'b' }
getPrefix ( /f?oo/ ); // => Set { 'f', 'o' }
getPrefix ( /o?k/i ); // => Set { 'o', 'O', 'k', 'K' }
getPrefix ( /[2-8]/ ); // => Set { '2', '3', '4', '5', '6', '7', '8' }
// Let's see some cases where we aren't able to narrow it down
getPrefix ( /^/ ); // => null
getPrefix ( /a?/ ); // => null
getPrefix ( /./ ); // => nullMIT © Fabio Spampinato