JSFiddle - React, Tailwind, and code Playground

by Denis Pavlov

JavaScript

generateSearchTextRegex('???#@#@');

function generateSearchTextRegex(filterText) {
    if (/\d{10}/.test(filterText))
        return filterText;
    
    var pats = '';
    var output = '';
    
    var isAnchorRight = filterText.substring(0, 1) === '*';
    var isAnchorLeft = filterText.substring(filterText.length - 1) == '*';
    filterText = filterText.replace(/\*/g, '');
    
    if (isAnchorRight && isAnchorLeft) {
        isAnchorRight = false;
        isAnchorLeft = false;
    }
    
    if (isAnchorLeft)
        output += '^';
    
    filterText.split('').forEach(function (c) {
        if ('!@#$%^&'.indexOf(c) != -1) {
            if (pats.indexOf(c) != -1)
                output += '\\' + (pats.indexOf(c) + 1);
            else {
                if (pats.length == 0)
                    output += '(\\d)';
                else if (pats.length == 1)
                    output += '((?!\\1)\\d)';
                else {
                    output += '(' + (pats.length + 1) + '(?!(\\1';
                    for (var i = 1; i < pats.length; i++)
                        output += '|\\' + (i + 1);
                    output += '))\\d)';
                }
                pats += c;
            }
        }
        else if (c == '?')
            output += '\\d';
        else if (c == '*')
            output += '\\d*';
        else
            output += c;
    });
    
    if (isAnchorRight)
        output += '$';
    
    return new RegExp(output);
}