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;
            }
        });         
    }
);
0

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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...
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.
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; } });
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
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.