admin管理员组

文章数量:1393051

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.

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.

Share Improve this question edited Apr 7, 2011 at 3:36 Chelo asked Apr 7, 2011 at 3:28 CheloChelo 413 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 10
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(""));
}

Um, I really don't think you need to clean anything here. If the user doesn't enter a valid regex, new RegExp(userInput) will just fail, it will never eval() the string.

本文标签: regexJavaScript RegExp to match strings using wildcards * andStack Overflow