javascript 将字符串转换为正则表达式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17081805/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert a string into a regular expression
提问by user2481168
I am using a very fine JavaScript library called "array-query"by Jacob Wright to do searches in arrays of objects.
我正在使用一个非常好的 JavaScript 库,它被 Jacob Wright称为“array-query”,用于在对象数组中进行搜索。
One method is regex()
where a regular expression can be included in parentheses like this: regex(/[^\w\s]/)
. If I hardcode the expression as I just showed it works fine. If I put the same expression in a variable first it does not work, like this:
一种方法是regex()
,其中一个正则表达式可被包括在这样的括号:regex(/[^\w\s]/)
。如果我像刚才展示的那样对表达式进行硬编码,它就可以正常工作。如果我首先将相同的表达式放入变量中,则它不起作用,如下所示:
var reg = "/[^\w\s]/";
regex(reg);
I was told
有人告诉我
You are putting quotes around your regex, making it a string. Remove the quotes.
您在正则表达式周围加上引号,使其成为字符串。删除引号。
Thus
因此
var reg = /[^\w\s]/;
regex(reg);
works fine.
工作正常。
Problem is I need to accept the user input from an textbox as part of the regular expression. For example if the user types in the letter z
it needs to get changed to /z/
. Even if I type in /z/
the textbox.value
returned has the same problem as a var reg = "/z/"
. If I hardcode var reg = /z/; regex(reg);
it works fine.
问题是我需要接受来自文本框的用户输入作为正则表达式的一部分。例如,如果用户输入字母,z
则需要将其更改为/z/
. 即使我在键入/z/
的textbox.value
返回有同样的问题作为var reg = "/z/"
。如果我硬编码var reg = /z/; regex(reg);
它工作正常。
How to make a input textbox value of "z"
into a form that is var reg = z;
?
Many many thanks for any help or ideas, hope this isn't too confusing.
如何将输入的文本框值"z"
变成 的形式var reg = z;
?非常感谢任何帮助或想法,希望这不会太混乱。
回答by Matyas
回答by Thelambofgoat
var reg = new RegExp("string");
回答by skparwal
You can do something like this:
你可以这样做:
var string = $('#input_id').val();
string = string.replace('/', '');
var regexpPattern = '/'+string+'/';
regex(regexpPattern);