Reputation: 27021
I have a regular expression as below:
var myVar = "some text";
var decimal = /^\s*(\+|-)?((\d+(\,\d+)?)|(\,\d+))\s*$/;
How to concat it with the myVar variable which is a string?
I tried the below but didn't work:
var decimal = new RegExp("/^\s*(\+|-)?((\d+(\" + myVar + "\d+)?)|(\" + myVar + "\d+))\s*$/");
Upvotes: 1
Views: 2747
Reputation: 11
You will need to escape the backslashes inside the string.
var decimal = new RegExp("/^\\s*(\\+|-)?((\\d+(\\,\\d+)?)|(\\,\\d+))\\s*$/" + myVar);
Upvotes: 0
Reputation: 8275
You don't need to add /
at the beginning and the end of new RegExp(...)
and \
should be escaped as mentioned by anubhava :
var decimal = new RegExp("^\\s*(\\+|-)?((\\d+(" + myVar + "\\d+)?)|(" + myVar + "\\d+))\\s*$");
Upvotes: 3
Reputation: 786359
Just from concatenation exercise you can do this:
var decimal = new RegExp("^(\\s*(\\+|-)?((\\d+(,\\d+)?)|(,\\d+))\\s*)" + myVar + "$");
Though keep in mind that myVar
can contain special regex meta characters as well that need to be escaped.
Upvotes: 2