用户输入RegExp不区分大小写 [英] user input to RegExp case insensitive
问题描述
我正在尝试对单个页面上的表执行不区分大小写的搜索,使用用户输入键,隐藏与contains不匹配的表行,并突出显示匹配的文本。隐藏/显示工作正常但匹配文本的突出显示无法使用RegExp和'i'。
I'm trying to do a case insensitive search on a table on a single page, using key up on user input, hide the table row that doesn't match with contains: and highlight the text that does match. The hide/show works fine but the highlight of matching text fails using RegExp and 'i'.
错误在chrome检查器中:从另一个构建一个RegExp时无法提供标志
error in chrome inspector: "Cannot supply flags when constructing one RegExp from another"
我搜索了这个,发现几乎没有。
I've searched this and found next to nothing.
如果我只是使用testcase变量并输入正确的capilisation,则突出显示有效。
the highlighting works if I just use the testcase variable and type in with correct capilisation.
任何建议都赞赏,我需要在英格兰赢得世界杯之前解决这个问题(...我可能有同样多的机会。): - D
Any advice appreciated, I need to crack this before england win the world cup (..i've probably got just as much chance.) :-D
$('input[name="search"]').live('keyup',function(){
var searchterm = $(this).val();
if(searchterm.length > 2) {
///make contains: non case sensitive
jQuery.expr[":"].contains = jQuery.expr.createPseudo(function(arg) {
return function( elem ) {
return jQuery(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
};
});
$('tr.data-row:contains("' + searchterm + '")').show();
$('tr.data-row:not(:contains("' + searchterm + '"))').hide();
$(".heading").hide();
$('.data-row p').each(function() {
var textcase = $(this).text();
var term = searchterm;
var text = new RegExp(/textcase/,"i");
$(this).html(text.replace(term,'<span style="color:#000;padding:3px; background-color:#afbbd7"><b>'+searchterm+'</b></span>'));
});
}
});
推荐答案
正则表达式
GOOD
-
new RegExp('chicken',' gm')
-
新的RegExp(/ chicken / gm)
new RegExp('chicken', 'gm')
new RegExp(/chicken/gm)
BAD
-
new RegExp('/ chicken /','gm')
-
new RegExp(/ chicken /,'gm')
new RegExp('/chicken/', 'gm')
new RegExp(/chicken/, 'gm')
传递字符串时作为正则表达式,'gm'部分需要是一个字符串并作为第二个参数传入。
When passing in a string as a Regular Expression the 'gm' part needs to be a string and passed in as the second argument.
当传入/.../作为正则表达式时'gm'部分需要在结束后立即进入/.
When passing in a /.../ as a Regular Expression the 'gm' part needs to go in right after the ending /.
这篇关于用户输入RegExp不区分大小写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!