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.
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
var reg = new RegExp("string");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With