Trev
Trev

Reputation: 33

user input to RegExp case insensitive

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'.

error in chrome inspector: "Cannot supply flags when constructing one RegExp from another"

I've searched this and found next to nothing.

the highlighting works if I just use the testcase variable and type in with correct capilisation.

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

} 

});

Upvotes: 1

Views: 2748

Answers (1)

M.Disch
M.Disch

Reputation: 63

Regular Expressions

GOOD

  1. new RegExp('chicken', 'gm')
  2. new RegExp(/chicken/gm)

BAD

  1. new RegExp('/chicken/', 'gm')
  2. new RegExp(/chicken/, '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.

When passing in a /.../ as a Regular Expression the 'gm' part needs to go in right after the ending /.

Upvotes: 6

Related Questions