rjg132234 rjg132234 - 4 months ago 20
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?


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