1

我需要验证存储在 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);
    }
  }
}

哪个不起作用=找不到任何东西。

问题:
如何为由变量名后跟任何字符组成的字符串创建正则表达式?

4

2 回答 2

3

但答案还是一样的:

使用构造函数允许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);
    }
  }
}
于 2013-01-28T14:15:19.337 回答
1

您在循环中的正则表达式始终是相同的,即: new RegExp("\\/abc/localstorage/ualldocs/aalldocs\\/*$") 将转换为: \/abc/localstorage/ualldocs/aalldocs\/*$

我真的不明白:

  1. 为什么要在循环中重新生成相同的正则表达式;
  2. 你想要达到的目标。

但是,您回答您的问题:

var someString = "something"
var myRegex = new RegExp(someString + '.*'); // creates a regex for the string made up of a variable 'someString' followed by any character: '.*'
于 2013-01-28T14:33:10.917 回答