1

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*$/");
3
  • What exactly do you want the resulting regex to match? Commented May 12, 2014 at 15:27
  • Apologies, I updated what is required exactly. Basically the "," should be replaced with the myVar. Commented May 12, 2014 at 15:28
  • Are you basically trying to make a pattern that will match 1,23 in one locale and 1.23 in another? I'd suggest using some i18n library like this or this. Commented May 12, 2014 at 15:35

3 Answers 3

3

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*$");
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

0

You will need to escape the backslashes inside the string.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.