views:

200

answers:

2

How to create regex pattern which is concatenate with variable, something like this:

var test ="52";
var re = new RegExp("/\b"+test+"\b/"); 
alert('51,52,53'.match(re));

Thanks

+5  A: 
var re = new RegExp("/\b"+test+"\b/"); 

\b in a string literal is a backspace character. When putting a regex in a string literal you need one more round of escaping:

var re = new RegExp("\\b"+test+"\\b"); 

(You also don't need the // in this context.)

bobince
The 'new' operator is not needed, as per http://bclary.com/2004/11/07/#a-15.10.3
J-P
There are many places where the constructor-function of a built-in type may be used both with or without `new`. However, for consistency with other objects where this may not hold true, and clarity in general, I would always use `new`.
bobince
+1  A: 

you can use

/(^|,)52(,|$)/.test('51,52,53')

but i suggest to use

var list = '51,52,53';
function test2(list, test){
    return !((","+list+",").indexOf(","+test+",") === -1)
}
alert( test2(list,52) )
Lauri