我需要一个正则表达式来验证if语句中的单个或多个城市:

时间:2014-05-06 14:05:58

标签: javascript

我有一个文本框,用户输入一个或多个由semicolor分隔的值。

示例:伦敦;

示例:伦敦;巴黎;

示例:多伦多;巴黎;纽约;伦敦;

我有一系列对象,如下所示:

    arr = [
    { name: "joe",   city: " Toronto;Paris;New York; London;"},
    { name: "nick",  city: " London;"},
    { name: "blast", city: " London;Paris;"}
];

我需要一个正则表达式来验证if语句中的单个或多个城市:例如,如果用户输入“London;”,那么我应该获得所有3个记录。如果用户输入“伦敦;巴黎;“那么我应该用”名字“”乔“和”爆炸“获得2条记录。

我为其他下拉菜做了类似的事情,但我对这种方法不满意:

var SubSpecialtiesArray = $("#SubSpecialtiesDropDown").multiselect("getChecked").map(function () {
    return this.value;
}).get();
var GeographicalLocationArray = $("#GeographicalLocationDropDown").multiselect("getChecked").map(function () {
    return this.value;
}).get();
for (var j = 0; j < gAssessorsInfoArray.length; j++) {
    if ((gAssessorsInfoArray[j].AvailableForRegular.indexOf(gServiceInfoArray[0].ServiceName) > -1 ||
          gAssessorsInfoArray[j].AvailableForCAT.indexOf(gServiceInfoArray[0].ServiceName) > -1) &&
          ($("#YearsOfExperienceDropDown").val() == "" ||
          $("#YearsOfExperienceDropDown").val() == gAssessorsInfoArray[j].YearsOfExperience) &&
          ($("#P104DropDown").val() == "" || $("#P104DropDown").val() == gAssessorsInfoArray[j].P104)) {
        if (SubSpecialtiesArray == "" && GeographicalLocationArray == "")
            AssessorsIDSArray.push(gAssessorsInfoArray[j].UserID);
        else {
            var FoundCounter = 0;
            for (var k = 0; k < SubSpecialtiesArray.length; k++) {
                if (gAssessorsInfoArray[j].SubSpecialties.indexOf(SubSpecialtiesArray[k]) > -1)
                    FoundCounter++;
            }
            if (SubSpecialtiesArray.length == FoundCounter)
                AssessorsIDSArray.push(gAssessorsInfoArray[j].UserID);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

仅针对一个搜索项目,请尝试以下操作:

arr = [
    { name: "joe",   city: " Toronto;Paris;New York; London;"},
    { name: "nick",  city: " London;"},
    { name: "blast", city: " London;Paris;"}
];

var search = "Paris;";

var result = arr.filter(function(element){
    return element.city.indexOf(search) !== -1;
});

然后,结果等于:

result == [
    { name: "joe",   city: " Toronto;Paris;New York; London;"},
    { name: "blast", city: " London;Paris;"}
];

如果您想测试多个城市:

假设:

var search = "Toronto;Paris;"

var searchArray = search.split(';').filter(function(element){return element.trim() !== ''});

var result = arr.filter(function(element){
    for(var i = 0; i < searchArray.length; i++){
        if(element.city.indexOf(searchArray[i].trim()) !== -1;){
            return true;
        }
    }
    return false;
});