0

How can I do something similar to the below

result = $.grep(data, function(e){ return e.firstname == name; });

with having name to be a regex expression, i.e. name starts with "Kevin*"

2
  • Are you asking for how to use a variable in a regular expression? Commented Aug 13, 2013 at 22:33
  • I didn't know I can do that. Commented Aug 13, 2013 at 22:41

1 Answer 1

2

Without testing, I'd suggest:

result = $.grep(data, function(e){
             return new RegExp('^Kevin').test(e.firstName);
         });

To use a variable then the above can be rewritten to:

var name = 'Kevin';
result = $.grep(data, function(e){
             return new RegExp('^' + name).test(e.firstName);
         });

References:

Sign up to request clarification or add additional context in comments.

2 Comments

David, you might want to lose the $ on your regex, or add a .* in.
@Adrian: agreed, I was focused on the == in the posted sample, rather than the 'starts with' written in the question-text. Thanks!

Your Answer

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