mawo
mawo

Reputation: 219

javascript regular expression: passing variable to regexp using word boundary

I have the following string:

"u_1,u_3,u_4,u_5,u_6,u_7,u_8,u_10,u_11,u_13,u_14,u_15,u_16,u_17,u_18,u_20"

I'd like to use a regular expression to filter for let's say "u_1" but it should not find "u_11" or "u_13", i.e., it needs to match exactly. So far so good. Also, the string I want to filter will be passed as a variable. What I have so far is the following:

var str = "u_1,u_3,u_4,u_5,u_6,u_7,u_8,u_10,u_11,u_13,u_14,u_15,u_16,u_17,u_18,u_20";
var setName = "u_1";
var re = new RegExp('/\b('+setName+')\b/g');
str.match(re);

Unfortunately there's something wrong with my regexp using the setName variable but I couldn't figure out how to fix it.

Upvotes: 1

Views: 254

Answers (1)

Avinash Raj
Avinash Raj

Reputation: 174706

Remove the forward slashes and escape the backslash one more time. Modifiers are passed as a separate parameter in RegExp constructor.

var re = new RegExp("\\b("+setName+")\\b", "g");

Example:

> var str = "u_1,u_3,u_4,u_5,u_6,u_7,u_8,u_10,u_11,u_13,u_14,u_15,u_16,u_17,u_18,u_20";
undefined
> setName = "u_1";
'u_1'
> var setName = "u_1";
undefined
> var re = new RegExp("\\b("+setName+")\\b", "g");
> re
/\b(u_1)\b/g
> str.match(re)
[ 'u_1' ]

Upvotes: 3

Related Questions