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 badges2 Answers
Reset to default 10function 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
版权声明:本文标题:regex - JavaScript RegExp to match strings using wildcards * and? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744662008a2618299.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论