-3

Hi everyone I'm new to javascript. how can i concatenate below variable

 var name = 'test';
 var query = /^ name / ;

db.users.find('name':query);    

Expected output

query = /^ test/;

I want query without double quotes please some one help me to go move forward

I tried like this

var query ='/^' +'name'+ '/';

but i'm getting result with double quotes "/^ test/".

FYI : I don't want double quotes outside

Thanks in advance

sportive
  • 3
  • 1

2 Answers2

0

It looks like you're trying to use a variable in a regular expression literal. I don't think the interpreter would understand that. However, you can pass a string to the regular expression constructor, and strings can be concatenated/interpolated all you like.

For example:

var name = 'test';
var query = new RegExp('^ ' + name);

or:

var name = 'test';
var query = new RegExp(`^ ${name}`);
David
  • 208,112
  • 36
  • 198
  • 279
  • need one help . need like this /^ test/i .help me on this – sportive Dec 02 '19 at 13:42
  • @sportive: The `i` would be known as a "flag", and is an optional second argument to the `RegExp` constructor: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp So for example you may have something like: `new RegExp('^ test', 'i')` – David Dec 02 '19 at 13:45
0

Instead of using the /regex/g syntax, you can construct a new RegExp object:

var name = "test";
var re = new RegExp(name, "g");
Ahmed Tounsi
  • 1,482
  • 1
  • 14
  • 24