1

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

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?

Thanks in advance.

1
  • 1
    i would consider changing the live emthod to on as it is deprecated, it will help in saving the hassle of updating such scripts Commented Jan 23, 2013 at 19:03

2 Answers 2

4

Use this :

new RegExp("\\b" + filter, 'i')

See the documentation on 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++;
     }
});
Sign up to request clarification or add additional context in comments.

2 Comments

this should work i know. but unfortunately this is not working. here is many checkpoints then how can i do this?
Did your code work before you tried to use a variable pattern ?
1

Using the constructor allows this for RegExp

$("#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++;
         }
    });
});

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.