Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript RegExp: Create regex with variable [duplicate]

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;
            }
        });         
    }
);
like image 667
jtmg.io Avatar asked Jan 19 '23 11:01

jtmg.io


2 Answers

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.

like image 87
gilly3 Avatar answered Jan 28 '23 20:01

gilly3


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
}
like image 24
jfriend00 Avatar answered Jan 28 '23 20:01

jfriend00