如何将变量传递给正则表达式 [英] how to pass a variable to a regex
本文介绍了如何将变量传递给正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个这样的查找语句
I have a find statement like this
collSession.find({"Venue.type": /.*MT.*/}).toArray(function (err, _clsSession)
{
console.log(_clsSession);
});
给出答案.但是我需要某个变量值,而不是那个杂乱的值MT. 如何实现呢? 谢谢.
It is giving answer.But i need to some value of variable instead of that harcoded value MT. How to achieve this ? Thanks.
更新,我尝试使用"/."+searchterm+"./" 它不起作用.
UPDATE I tried like "/."+searchterm+"./" Its not working.
推荐答案
Instead of using the inline syntax to create a regular expression, you can also use the RegExp object to create one based on a string
var searchPhrase = "MT";
var regularExpression = new RegExp(".*" + searchPhrase + ".*");
collSession.find({"Venue.type": regularExpression}) [...]
这篇关于如何将变量传递给正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文