简体   繁体   中英

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}

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

First, it may be appropriate to use RegExp.test . Second, creating a RegExp object you shouldn't use RegExp literal characters ('/').

So your code becomes:

var str1 = 'abcd/pqrst'
   ,str2 = 'pqr'
   ,re = RegExp('^'+str2+'.*');

if (re.test(str1)) { /* do things */}

Third, the RegExp ( /^pqr.*/ ) will test false for str1 . The equivalent of WHERE "str1" LIKE '%str2%'; is as simple as RegExp(str2,'i').test(str1) (note the i modifier (case insensitive test)), or even just ~str.indexOf(str2) (see @ Jeff Bowmans answer).

If all you need to do is to confirm that a string occurs in the middle of a different string, use str1.indexOf(str2) >= 0 . In other languages this would be equivalent to str1.contains(str2) , though Javascript strings lack a contains method.

If you do want to put str2 in the middle of the regular expression, be sure to escape it .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM