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 inj开发者_C百科ections (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.
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.
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论