RegExp JavaScript to match strings using * and? Wildcards

I have a list of names, and I need a function so that the user can filter them using wildcards * and? (any string and any character.) I know that I need to clear user input to avoid syntactic injections (intentional or random), but I don't know how much I need to clear.

Why do I need to replace * and? from 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.

+4
source share
2 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("")); } 
+10
source

Um, I really don't think you need to clean anything here. If the user does not enter a valid regular expression, new RegExp(userInput) simply fail, it will never be eval() for the string.

0
source

Source: https://habr.com/ru/post/1347026/


All Articles