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