3

I'm searching an array of objects using jquery grep and would like to include wildcards in the search. For example, I have an array as follows:

courses = [
{code: 'ENCH3TH', otherFields: otherStuff},
{code: 'ENCH3THHS1', otherFields: otherStuff},
{code: 'ENCH3TH2', otherFields: otherStuff},
{code: 'ENCH4RT', otherFields: otherStuff},
{code: 'ENCH4MT', otherFields: otherStuff}]

I'd like to get all the courses with the ENCH3TH prefix. I have attempted

var resultSet = $.grep(courses, function(e){ return e.code == 'ENCH3TH/'; });

..to no avail (note the use of the '/' after 'ENCH3TH' as the wildcard).

1
  • In what language is / a wildcard? Commented Sep 12, 2013 at 7:34

1 Answer 1

4

You can use String.indexOf() here, = will not work with wild chars

var resultSet = $.grep(courses, function (e) {
    return e.code.indexOf('ENCH3TH') == 0;
});

Demo: Fiddle

Or use regex

var regex = /^ENCH3TH/
var resultSet = $.grep(courses, function (e) {
    return regex.test(e.code);
});

Demo: Fiddle

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

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.