rjg132234 rjg132234 - 2 months ago 9
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.

e.g.

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

Try this (I use ):

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

Note

  • .* 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