0

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?

2
  • What are the / around .* for? Commented Oct 6, 2016 at 21:18
  • 2
    Write the regex, then write JS Code to build that. don't just start slapping variables and operators around without a clear idea of what you're trying to accomplish. Commented Oct 6, 2016 at 21:18

5 Answers 5

3

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, this 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
  • to ensure Test1 is at the beginning, i put ^ anchor, and for Test2 at the end, I added $ anchor
  • the regex constructor is not ReGex but RegExp (note the trailing p)
Sign up to request clarification or add additional context in comments.

6 Comments

. does not match any character in JS regex patterns.
For a "dot-all" in JS, some people use [\s\S]* or [^]*
.* is what's OP try to do, and is what I want to do to it's his needs
Won't work. Try 'Test1Test2Test3' (shouldn't match, but will...)
you should enforce the beginning of the string with ^ otherwise you'll get wrong true , ex:hi Test1Test2
|
2

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

Comments

2

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'));

Comments

1

if you know the beginning and the end you can enforce that:

var re = new RegExp("^" + t1 + ".*" + t2 + "$");

Comments

0

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 :-)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.