在jQuery中的正则表达式中使用变量 [英] use variable in regular expression in jquery
本文介绍了在jQuery中的正则表达式中使用变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
某些专家可能会很容易提出这个问题,但对我来说似乎很难.我想在正则表达式模式中使用variable
.
May be it will be a very easy question some of expert but seems difficult to me. I want to use a variable
in pattern of regular expression.
$("#srcbtn .btnPage").live("click",function(){
var filter = $(this).val(), count = 0;
$(".checkpoint").each(function () {
if ($(this).find(".chpdetails .chkpname").text().search(new RegExp(/\b filter /i)) < 0) {
$(this).hide();
} else {
$(this).show();
count++;
}
});
});
,但过滤器变量在if
条件下不起作用.这段代码的目的是搜索一个以filter
变量值开头的单词,即A,B等.
but the filter variable doesn't work in if
condition. the purpose of this code is to search a word which is start with filter
variable's value i.e. A, B etc. How can i do this?
谢谢.
推荐答案
使用此方法:
new RegExp("\\b" + filter, 'i')
请参见有关RegExp的文档
如果有许多检查点,则可能应该在进入循环之前构建regexp对象,而不是在每次迭代时都构建它:
If you have many checkpoints, you should probably build the regexp object before entering the loop instead of building it at each iteration :
var r = new RegExp("\\b" + filter, 'i');
$(".checkpoint").each(function () {
if ($(this).find(".chpdetails .chkpname").text().search(r) < 0) {
$(this).hide();
} else {
$(this).show();
count++;
}
});
这篇关于在jQuery中的正则表达式中使用变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文