1

i have a little problem with .search

this is the code

// filter - posts
jQuery('.filter_by').live('click',function(){
    var target_fi = jQuery(this);
    var target_cat = target_fi.parents('.cat').children('.namechanger').val(); 
    target_fi.next().fadeIn(100);


    var cat_all = target_fi.prev().find("option").each(function(i){
        if(jQuery(this).attr('data-cats').search(target_cat)  == -1){
            jQuery(this).css({"display":"none"});
        }
    });


});

I want to use the variable target_cat with .search

I can't do this .search(/target_cat/)

1
  • 1
    try new RegExp(target_cat) Commented Mar 11, 2013 at 10:06

3 Answers 3

1

If you want to make a regular expression out of the string value of target_cat, then you can do this:

var mySearchTerm = new RegExp(target_cat);

...

if(jQuery(this).attr('data-cats').search(mySearchTerm)  == -1){
Sign up to request clarification or add additional context in comments.

2 Comments

It is unnecessary to declare a new variable for that.
@Amberlamps I suppose, but it highlights how it needs to be done.
1

You need to create RegExp object and pass that to search method

if(jQuery(this).attr('data-cats').search(new RegExp(target_cat)) == -1 )){
...
}

Comments

1

To convert anything into a regular expression, simply drop it into the constructor:

var something = "foobar"; var expression = new RegExp(something, 'i');

note the second argument for flags. See RegExp for more info on the constructor and Regular Expressions for details on how things work.

If your something contains "special characters" (such as |, ?, {) you need to escape them, if you want them to be meant literally (/foo?/ vs. /foo\?/). Here's a function that'll esacpe all relevant characters for you:

function escapeRegEx(string) {
  return string.replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
}

  • You are using jQuery.live, but should use jQuery.on instead
  • You are using .search() when .match() suffices
  • You are using the explicit jQuery(this).css({"display":"none"}); when jQuery(this).hide(); suffices
  • note that you are repeating jQuery(this) in your loop - one should be enough - variables are your friends.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.