View Full Version : Resolved RegExp() and Variables

10-07-2011, 09:27 PM
hello all

I am working on a keyword filter and am stuck on something that I am hoping someone has more experience with

my problem is that I am trying to pass a regular expression as a variable to the RegExp() function in javascript but it does not seem to be working

example below

var X = '^(?=.*?(';
var Y = 'dog))(?=.*?(cat))(?=.*?(mouse'; // this gets created dynamically
var Z = ')).*$';

var A = X + Y + Z;
// result is ^(?=.*?(dog))(?=.*?(cat))(?=.*?(mouse)).*$ and is a valid and tested expression

var B = new RegExp(A, 'i');

I want to pass B to a search() function but it does not seem to be accepted as a valid expression anymore

thanks for any help

10-07-2011, 09:33 PM
if you want to pass a regExp as a variable in javascript you would do so with /regexp/

var B = /[0-9]/;

10-07-2011, 09:35 PM
or in your case:

var B = /^(?=.*?(dog))(?=.*?(cat))(?=.*?(mouse)).*$/

10-07-2011, 09:40 PM
I would expect the following to work, but I don't know what your regExp catches, so I don't know how to test it

var X = /^(?=.*?(/;
var Y = /dog))(?=.*?(cat))(?=.*?(mouse/;
var Z = /)).*$/;

var A = X + Y + Z;

var B = new RegExp(A, 'i');

10-07-2011, 09:51 PM
I found a way to test, I used the following code (it's a moderation of your original attempt, but with a regExp that I have verified) and it worked just fine.

var X = '[0-9]|';
var Y = '[a-z]';

var A = X + Y;

var B = new RegExp(A, 'g');
<span onclick="this.innerHTML=this.innerHTML.replace(B,'')">lshsdj--LJKLK--87678</span> maybe you should've specified global and case insensitive, not just the latter?

10-07-2011, 10:44 PM
thanks !!

I think you helped me figure out that my real problem is further down the particular filtering script that I am working on and not necessarily the construction of the regex

after I research that a little there may be another thread on the way :)