最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

regex - passing variable in regular expression in javascript for string match - Stack Overflow

programmeradmin3浏览0评论

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}

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}
Share Improve this question asked Oct 15, 2012 at 5:37 user930514user930514 9272 gold badges17 silver badges28 bronze badges 1
  • @elclanrs: This doesnt work : var re = new RegExp("/^.*"+ str2 + ".*/"); if(str1.match(re){ //do something} – user930514 Commented Oct 15, 2012 at 5:41
Add a ment  | 

3 Answers 3

Reset to default 7

Here is a quick jsFiddle for you to try

http://jsfiddle/jaschahal/kStTc/

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

More details here

http://www.w3schools./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 bees:

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.

发布评论

评论列表(0)

  1. 暂无评论