Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a string into a regular expression [duplicate]

I am using a very fine JavaScript library called "array-query" by Jacob Wright to do searches in arrays of objects.

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:

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.

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.

like image 629
user2481168 Avatar asked Oct 21 '22 07:10

user2481168


2 Answers

You should do

var regex = new RegExp('your regex string');

Basically you can think of

var regex = /pattern/modifiers;

as

var regex = new RegExp(pattern,modifiers);

Read more about it at: MDN or w3schools

like image 167
Matyas Avatar answered Oct 27 '22 09:10

Matyas


var reg = new RegExp("string");
like image 29
Thelambofgoat Avatar answered Oct 27 '22 07:10

Thelambofgoat