Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /** Converts a wildcard string into a regexp
- * @param {string} input - The wildcard string to convert
- * @param {boolean} caseSensitive - If truthy the returned regexp will be case sensitive
- * @returns {RegExp}
- */
- export default function wildcard(input, caseSensitive) {
- input = input
- // Escape characters that would alter the regex
- .replace(/[\(\)\[\]\{\}\^\$\\\/\.\+]/g, '\\$&')
- // wildcard &
- .replace(/&(?= |$)/g, '\\S+')
- // wildcard ? and *
- .replace(/(?:^(?=$|[^?*]))|(?:(?<=^|[^?*])$)|(?:[?*]+)/g, (match, pos) => {
- // indicates if the match started at the beginning of the input
- let atStart = pos === 0,
- // indicates if the match ends at the end of the input
- atEnd = pos + match.length === input.length,
- // indicates if the match is in the middle of the input
- isInner = !atStart && !atEnd,
- // indicates if the match contains a *
- hasStar = match.indexOf('*') > -1,
- // counts the number of ?'s in the match
- count = (match.match(/\?/g) || []).length,
- // will contain the result
- res = ''
- // if the input consists of only *'s, return an empty string
- // the regex will match any input
- if (atStart && atEnd && hasStar && !count) {
- return res;
- }
- // if the input doesn't start with a combo of ? and *'s that include a *
- // anchor the regex to the start of the string
- if (atStart && !hasStar) {
- res += '^';
- }
- // if only one ? is present use [\s\S]+ format
- if (count === 1) {
- res += '[\s\S]' + ((isInner && hasStar) ? '+' : '');
- // if more than one ? is present use [\s\S]{count,} format
- } else if (count > 1) {
- res += `[\s\S]{${count}${(isInner && hasStar) ? ',' : ''}}`;
- // if only *'s were matched and the match occured in the middle of the input
- } else if (isInner && hasStar) {
- res += [\s\S]*
- }
- // if the input does not end with a combo of ? and *'s that include a *
- // anchor the regex to the end of the string
- if (atEnd && !hasStar) {
- res += '$'
- }
- // return the result
- return res;
- });
- return new RegExp(input, !caseSensitive ? 'i' : '');
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement