Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript RegExp to match strings using wildcards * and?

I have a list of names and I need a feature for the user to filter them using the wildcards * and ? (any string and any character.) I know I need to clean the user input in order to avoid syntax injections (intentional or accidental), but I don't know how much will I need to clean.

For what do I need to replace the * and ? from the user input?

var names = [...];
var userInput = field.value;

/* Replace * and ? for their equivalent in regexp */
userInput = userInput.replaceAll(...);
userInput = userInput.replaceAll(...);

 /* clean the input */
userInput = userInput.replaceAll(...);
userInput = userInput.replaceAll(...);
...

var regex = new Regexp(userInput);

var matches = [];
for (name in names) {
    if (regex.test(name)) {
        matches.push(name);
    }
}

/* Show the results */

Thanks.

like image 878
Chelo Avatar asked Dec 27 '22 22:12

Chelo


1 Answers

function globToRegex (glob) {
    var specialChars = "\\^$*+?.()|{}[]";
    var regexChars = ["^"];
    for (var i = 0; i < glob.length; ++i) {
        var c = glob.charAt(i);
        switch (c) {
            case '?':
                regexChars.push(".");
                break;
            case '*':
                regexChars.push(".*");
                break;
            default:
                if (specialChars.indexOf(c) >= 0) {
                    regexChars.push("\\");
                }
                regexChars.push(c);
        }
    }
    regexChars.push("$");
    return new RegExp(regexChars.join(""));
}
like image 167
Thomas Eding Avatar answered Jan 13 '23 23:01

Thomas Eding