Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing variable in regular expression in javascript for string match

Suppose i need to use string match in javascript to get a result equivalent to the LIKE operator.

WHERE "str1" LIKE '%str2%';

The below match expression works.

var str1="abcd/pqrst"; 
var str2 =  "pqr";

if(str1.match(/^.*pqr.*/)){ //do something};

But i need to pass a variable instead of pqr, something like the below statement.Please help.

//Wrong
var re = new RegExp("/^.*"+ str2 + ".*/"); 
if(str1.match(re){ //do something}
like image 737
user930514 Avatar asked Mar 19 '26 13:03

user930514


1 Answers

Here is a quick jsFiddle for you to try

http://jsfiddle.net/jaschahal/kStTc/

var re = new RegExp("^.*"+str2+".*","gi"); 
// second param take flags

More details here

http://www.w3schools.com/jsref/jsref_obj_regexp.asp

You can also use contains()/indexOf() functions for these simple checks

like image 177
Jaspreet Chahal Avatar answered Mar 21 '26 03:03

Jaspreet Chahal