[英]How do I create a regex for a string made up of a variable name followed by any character in Javascript?
I need to verify "pathnames" of items stored in localStorage (pathname being a string
like: abc/localstorage/ualldocs/aalldocs
in order to filter whats in localstorage. 我需要验证存储在localStorage中的项目的“路径名”(路径名是一个
string
如: abc/localstorage/ualldocs/aalldocs
,以便过滤localstorage中的内容。
Right now I'm trying this: 现在我正在尝试这个:
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);
}
}
}
Which does not work = does not find anything. 哪个不起作用=找不到任何东西。
Question: 题:
How do I create a regex for a string made up of a variable name followed by any character? 如何为由变量名后跟任何字符组成的字符串创建正则表达式?
But the answer is still the same: 但答案仍然是一样的:
Using the constructor allows this for RegExp 使用构造函数允许这用于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);
}
}
}
Your regex in the loop is always the same, being: new RegExp("\\\\/abc/localstorage/ualldocs/aalldocs\\\\/*$")
which will translate into: \\/abc/localstorage/ualldocs/aalldocs\\/*$
循环中的正则表达式始终是相同的,是:
new RegExp("\\\\/abc/localstorage/ualldocs/aalldocs\\\\/*$")
将转换为: \\/abc/localstorage/ualldocs/aalldocs\\/*$
I don't really understand: 我真的不明白:
However, your answering your question: 但是,您回答了以下问题:
var someString = "something"
var myRegex = new RegExp(someString + '.*'); // creates a regex for the string made up of a variable 'someString' followed by any character: '.*'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.