The Light
The Light

Reputation: 27021

How to concat a regex expression with a string variable?

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

Answers (3)

nythgar
nythgar

Reputation: 11

You will need to escape the backslashes inside the string.

var decimal = new RegExp("/^\\s*(\\+|-)?((\\d+(\\,\\d+)?)|(\\,\\d+))\\s*$/" + myVar);

Upvotes: 0

Samuel Caillerie
Samuel Caillerie

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

anubhava
anubhava

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

Related Questions