开发者

Searching for name using JavaScript

When I type G in the field and it filters out all the names whose names contain g in any part of their name. I w开发者_JAVA技巧ant only to filter which starts with G. To sort this, i added something like this.

patientSearchResult[i].LastName.toUpperCase().charAt(0)

But now when i type Gr. i don't get Greg's result... why?


You could use a regular expression coupled with an array filter for this. Try this:

var patients = [
    "Greg",
    "Anna",
    "Slartibartfarst"
    ];

var input = "Gr";
var re = new RegExp(input+'.+$', 'i');
patients = patients.filter(function(e, i, a){
    return e.search(re) != -1;
});
console.log(patients);

http://jsfiddle.net/2R44X/


charAt returns just the character at the specified index.

You could use patientSearchResult[i].LastName.toUpperCase().substr(0,2) where 2 should be replaqced with the length of the string you're searching for.


For a more generic solution, you could use Array.filter with regexp searches to make query functions:

var patientRecord = [
        {firstname: 'Bob',lastname: 'Grown'},
        {firstname: 'Alexa',lastname: 'Ace'},
        {firstname: 'Chris',lastname: 'Green'}
    ];

var makeQuery = function(property, regexp) {
        // return a callback function for filter, see MDC docs for Array.filter
        return function(elem, index, array) {
            return elem[property].search(regexp) !== -1;
        };
    };

var q = makeQuery('lastname', /^g/i); // ^ = from beginning, i = "ignore case"

patientRecord.filter(q);

Console output:

[
    {
        firstname: "Bob",
        lastname: "Grown",
        __proto__: Object
    }, 
    {
        firstname: "Chris",
        lastname: "Green",
        __proto__: Object
    }
]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜