-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

5
  • what is db.users.find? Commented Nov 29, 2019 at 12:39
  • try this var query =`'/^name/'`; Commented Nov 29, 2019 at 12:39
  • @Jamiec as much I know db.users.find is nothing but mongodb query Commented Nov 29, 2019 at 12:41
  • find query for name. please disregard that. Commented Nov 29, 2019 at 12:41
  • well its relevant - as maybe there is a way to parameterize it with the library you're using. ie, are you attempting to "re-invent the wheel"? Basically, I think this is an XY Problem! Commented Nov 29, 2019 at 12:42

2 Answers 2

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

2 Comments

need one help . need like this /^ test/i .help me on this
@sportive: The i would be known as a "flag", and is an optional second argument to the RegExp constructor: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… So for example you may have something like: new RegExp('^ test', 'i')
0

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

var name = "test";
var re = new RegExp(name, "g");

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.