ClaraU
ClaraU

Reputation: 957

Passing variable to regular expression

I have a regular expression

var p = /\bj[^\b]*?\b/gi;

I need to make the 'j' a variable value, but when i do the following;-

var p = new RegExp('\\b'+'${0}'+'[^\\b]*?\\b', 'gi');

I get error -

Uncaught SyntaxError: Invalid regular expression: /\b${0}[^\b]*?\b/: Nothing to repeat 

Any help appreciated.

Thank you

Upvotes: 0

Views: 165

Answers (3)

ClaraU
ClaraU

Reputation: 957

Sorry guys, I should have been more clear, the value '{0}' is a token that will be replaced and not a variable. The error was occurring because '{' and '}' are special characters in regular expressions.

So changing the token pattern fixed the problem

var p = new RegExp('\\b'+'%text%'+'[^\\b]*?\\b', 'gi');

Upvotes: 0

Andrew Clark
Andrew Clark

Reputation: 208395

I think you want the following:

var p = new RegExp('\\b'+${0}+'[^\\b]*?\\b', 'gi');

With the quotes around ${0} you are just constructing a string with those characters, instead of inserting the variable value.

Upvotes: 1

EEP
EEP

Reputation: 725

Putting a variable within quotation marks as you have done with '${0}' is going to cause that to be treated as a string. If you remove the quotation marks from around it then it will be treated as a variable.

Upvotes: 0

Related Questions