admin管理员组文章数量:1391811
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?
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?
Share Improve this question edited Oct 6, 2016 at 21:17 Barmar 784k57 gold badges548 silver badges659 bronze badges asked Oct 6, 2016 at 21:16 rjg132234rjg132234 6203 gold badges10 silver badges21 bronze badges 2-
What are the
/
around.*
for? – Barmar 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 acplish. – Marc B Commented Oct 6, 2016 at 21:18
5 Answers
Reset to default 3Try 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
Note
.*
as stated in ments, 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 forTest2
at the end, I added$
anchor - the regex constructor is not
ReGex
butRegExp
(note the trailingp
)
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
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'));
if you know the beginning and the end you can enforce that:
var re = new RegExp("^" + t1 + ".*" + t2 + "$");
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 :-)
本文标签: How to concat two javascript variables and regex expressionStack Overflow
版权声明:本文标题:How to concat two javascript variables and regex expression - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744766467a2624072.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论