4
我有一個名稱列表,我需要一個功能供用戶使用通配符*和?進行過濾。 (任何字符串和任何字符)。我知道我需要清理用戶輸入以避免語法注入(有意或無意),但我不知道需要清理多少。使用通配符*和?匹配字符串的JavaScript RegExp
對於我需要替換*和?來自用戶輸入?
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 */
謝謝。
在根正則表達式中添加^ $。 – 2011-04-09 01:54:33
感謝您發佈此方法。我只是將它擴展爲可選的不區分大小寫,所以我最後兩行是: if(insensitive){modifiers ='i'};返回新的RegExp(regexChars.join(「」),modifiers); – Lee 2012-07-06 16:43:57