rjg132234 rjg132234 - 1 year ago 105
Javascript Question

How to concat two javascript variables and regex expression

I want to be able to concat two variables with a regular expression in the middle.


var t1 = "Test1"
var t2 = "Test2"
var re = new RegEx(t1 + "/.*/" + t2);

So the result I want is an expression that matches this..

"Test1 this works Test2"

How do I get a result where I am able to match any text that has Test1 and Test2 on the ends?

Answer Source

Try this (I use ):

> var t1 = "Test1"
> var t2 = "Test2"
> var re = new RegExp(t1 + '.*' + t2);
> re
> re.test("Test1  this works   Test2")


  • .* as stated in comments means any character repeated from 0 to ~
  • the slashes are automagically added when calling the RegExp constructor, but you can't have nested unprotected slashes delimiters
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download