4

Possible Duplicate:
Javascript Regexp dynamic generation?

I am trying to create a new RegExp with a variable; however, I do not know the sytax to do this. Any help would be great!

I need to change this: (v.name.search(new RegExp(/Josh Gonzalez/i)) != -1) change it to this: (v.name.search(new RegExp(/q/i)) != -1). I basically need to replace the "josh" with the variable q ~ var q = $( 'input[name="q"]' ).val();

Thanks for the help

$( 'form#search-connections' )
    .submit( function( event )
    {
        event.preventDefault();
        var q = $( 'input[name="q"]' ).val();

        console.log( _json );

        $.each( _json, function(i, v) {

        //NEED TO INSERT Q FOR JOSH 

            if (v.name.search(new RegExp(/Josh Gonzalez/i)) != -1) {

                alert(v.name);
                return;
            }
        });         
    }
);
Community
  • 1
  • 1
jtmg.io
  • 235
  • 5
  • 13

2 Answers2

8

Like so:

new RegExp(q + " Gonzalez", "i");

Using the / characters is how to define a RegExp with RegExp literal syntax. To create a RegExp from a string, pass the string to the RegExp constructor. These are equivalent:

var expr = /Josh Gonzalez/i;
var expr = new RegExp("Josh Gonzalez", "i");

The way you have it you are passing a regular expression to the regular expression constructor... it's redundant.

gilly3
  • 87,962
  • 25
  • 144
  • 176
  • Hmmm. When I first posted my answer, your answer didn't have the same code as my answer (thus why I posted) and now you do. Interesting... – jfriend00 Oct 19 '11 at 23:51
  • Ya, I usually edit my answers a few times in the first couple of minutes after I first post. Post, re-read question, double-check answer, make corrections, repeat until I'm satisfied. I don't want to be too slow, but I also want to be accurate. You must've seen my original post before I got my edits in. – gilly3 Oct 19 '11 at 23:55
  • This worked great! Here is the finally code: var q = $( 'input[name="q"]' ).val(), r = new RegExp( q, 'i'); $.each( _json, function(i, v) { if (v.name.search(r) != -1) { alert(v.name); return; } }); – jtmg.io Oct 20 '11 at 03:22
1

You just need to build the string you want using string addition and pass it to the RegExp constructor like this:

var q = $( 'input[name="q"]' ).val();
var re = new RegExp(q + " Gonzalez", "i");
if (v.name.search(re) != -1) {
    // do your stuff here
}
jfriend00
  • 683,504
  • 96
  • 985
  • 979