Reputation: 620
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?
Upvotes: 0
Views: 3342
Reputation: 185005
Try this (I use nodejs):
> var t1 = "Test1"
> var t2 = "Test2"
> var re = new RegExp('^' + t1 + '.*' + t2 + '$')
> re
/^Test1.*Test2$/
> re.test("Test1 this works Test2")
true
.*
as stated in comments, this means any character repeated from 0 to ~RegExp
constructor, but you can't have nested unprotected slashes delimitersTest1
is at the beginning, i put ^
anchor, and for Test2
at the end, I added $
anchorReGex
but RegExp
(note the trailing p
)Upvotes: 3
Reputation: 18734
if you know the beginning and the end you can enforce that:
var re = new RegExp("^" + t1 + ".*" + t2 + "$");
Upvotes: 1
Reputation: 663
Take care that the value of the two variables do not contain any special regex characters, or transform those values to escape any special regex characters.
Of course, also make sure that the regex in between matches what you want it to :-)
Upvotes: 0
Reputation: 46323
You don't need regex:
var t1 = 'Test1';
var t2 = 'Test2';
var test = function(s) { return s.startsWith(t1) && s.endsWith(t2); };
console.log(test('Test1 this works Test2'));
console.log(test('Test1 this does not'));
Upvotes: 2
Reputation: 66
The RegExp constructor takes care of adding the forward slashes for you.
var t1 = "Test1";
var t2 = "Test2";
var re = new RegExp(t1 + ".*" + t2);
re.test("Test1 some_text Test2"); // true
Upvotes: 2