我需要验证存储在localStorage中的项目的“路径名”(路径名为string
,如:abc/localstorage/ualldocs/aalldocs
,以便过滤localstorage中的内容。
现在我正在尝试这个:
priv.localpath = "abc/localstorage/ualldocs/aalldocs";
for (i in localStorage) {
if (localStorage.hasOwnProperty(i)) {
s = new RegExp('\\/' + priv.localpath + '\\/.*$');
if (s.test(i)) {
value = localStorage.getItem(i);
console.log( value );
} else {
console.log( "not found: "+i);
}
}
}
哪个不起作用=找不到任何东西。
问题:
如何为由变量名后跟任何字符组成的字符串创建正则表达式?
答案 0 :(得分:2)
但答案仍然是一样的:
使用构造函数允许RegExp
priv.localpath = "abc/localstorage/ualldocs/aalldocs";
for (i in localStorage) {
if (localStorage.hasOwnProperty(i)) {
s = new RegExp(priv.localpath + '\\/*$', "i")
if (s.test(i)) {
value = localStorage.getItem(i);
console.log( value );
} else {
console.log( "not found: "+i);
}
}
}
答案 1 :(得分:1)
循环中的正则表达式总是一样的,是:
new RegExp("\\/abc/localstorage/ualldocs/aalldocs\\/*$")
这将转化为:
\/abc/localstorage/ualldocs/aalldocs\/*$
我真的不明白:
但是,你回答了你的问题:
var someString = "something"
var myRegex = new RegExp(someString + '.*'); // creates a regex for the string made up of a variable 'someString' followed by any character: '.*'