1

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

} 

});
Trev
  • 33
  • 1
  • 4
  • 2
    var text = new RegExp(/textcase/,"i"); should be var text = new RegExp(text,"i"); and replace is called on strings, not regexp's, which should be the first arg to strHaystack.replace(rxNeedle, strNewText) – dandavis Jun 09 '14 at 20:15
  • Thanks for the reply, ok i'm probably being dim and you may have to slow up for me :). I understand that you're saying I can't use replace on regexp (is that the error being reported?) I don't get RegExp(text,"i") what does text, refer to here? many thanks again – Trev Jun 09 '14 at 20:34
  • @dandavis ok got it, I was getting the needle and the haystack mixed up :) works now with changes as below. A massive thanks. `var textcase = jx$(this).text(); var term = searchterm; var searchtermRX = new RegExp(searchterm,"i"); $(this).html(textcase.replace(searchtermRX,''+searchterm+''));` – Trev Jun 09 '14 at 21:19

1 Answers1

6

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

M.Disch
  • 63
  • 2
  • 7