遍历数组并比较多个子字符串

时间:2018-10-11 14:33:34

标签: javascript

我有一个包含字符串的变量。可能是:

var = destination // France, Spain and Italy

字符串中的重要子字符串为FranceSpainItaly

我还有一个数组:

var countryList = ["Spain", "the United States", "France", "Italy", "Greece", "Portugal"];

我需要循环destinationcountryList,并停在第一个值以匹配任何提到的子字符串。在这种情况下,西班牙应该比法国更早匹配。

然后我需要将匹配的值存储为变量。

注释:该变量可以包含任何目标位置,数组是重要的层次结构,它将选择字符串中最重要的目标位置并将其存储。

3 个答案:

答案 0 :(得分:1)

Array.prototype.find遍历数组,并返回回调函数返回的第一个值true

const foundMatch = countryList.find(name => destination.includes(name));

如果您需要ES5解决方案,则可以使用:

function findMatch(countryList, destination) {
  for (var i = 0; i < countryList.length; i++) {
    if (destination.indexOf(countryList[i]) !== -1) {
      return countryList[i];
    }
  }

  return null;
}

答案 1 :(得分:0)

您可以这样做:

 public Mono<Object> addUserDetails(UserDTO userDTO) {

 if (userDTO.getName = = Null) {
           setCustomizeException // here I am setting customize error

    String responseBody = getCustomizeException();
            return  Mono
                    .just(ResponseEntity
                            .badRequest()
                            .body(responseBody));
        }


    setCustomizeException // here I am setting customize error

    String responseBody = getCustomizeException();

    Repository.save(user); 

    return  Mono.just(ResponseEntity.badRequest().body(responseBody));

    }

或者如果您需要索引:

found = null;
countryList.forEach((c) => {
  if (destination.toLowerCase().indexOf(c.toLowerCase()) !== -1)
  {
    found = c;
  }
});

// found is null or the string of the country

答案 2 :(得分:-1)

var  destination = "France, Spain and Italy";
var countries = destination.split(' ');
var first_country;
var countryList = ["Spain", "the United States", "France",   "Italy", "Greece", "Portugal"];
for(var i=0;i<countries.length;i++){
    if(countryList.indexOf(countries[i].replace(/[^0-9a-z]/gi, ''))>-1){
        first_country= countries[i];
      }

console.log(first_country);