[javascript] JavaScript .includes () 메서드에 대한 여러 조건

.includes 메서드에 여러 조건을 추가하는 방법이 있는지 궁금합니다. 예를 들면 다음과 같습니다.

    var value = str.includes("hello", "hi", "howdy");

쉼표에 “또는”이 있다고 상상해보십시오.

이제 문자열에 hello, hi 또는 howdy 가 포함되어 있는지 묻습니다 . 따라서 조건 중 하나만 참일 경우에만 해당됩니다.

그렇게하는 방법이 있습니까?



답변

하나의 경우에도 작동하며 조건 중 하나만 참입니다.

var str = "bonjour le monde vive le javascript";
var arr = ['bonjour','europe', 'c++'];

function contains(target, pattern){
    var value = 0;
    pattern.forEach(function(word){
      value = value + target.includes(word);
    });
    return (value === 1)
}

console.log(contains(str, arr));


답변

여기에.some 언급 된 방법을 사용할 수 있습니다 .

some()메서드 는 배열의 하나 이상의 요소 가 제공된 함수에서 구현 한 테스트를 통과 하는지 테스트합니다 .

// test cases
var str1 = 'hi, how do you do?';
var str2 = 'regular string';

// do the test strings contain these terms?
var conditions = ["hello", "hi", "howdy"];

// run the tests against every element in the array
var test1 = conditions.some(el => str1.includes(el));
var test2 = conditions.some(el => str2.includes(el));

// display results
console.log(str1, ' ===> ', test1);
console.log(str2, ' ===> ', test2);


답변

를 사용 includes()하면 아니요,하지만 다음을 통해 REGEX로 동일한 결과를 얻을 수 있습니다 test().

var value = /hello|hi|howdy/.test(str);

또는 단어가 동적 소스에서 오는 경우 :

var words = array('hello', 'hi', 'howdy');
var value = new RegExp(words.join('|')).test(str);

REGEX 접근 방식은 단어를 다른 단어의 하위 문자열이 아닌 실제 단어로 일치시킬 수 있기 때문에 더 나은 아이디어 입니다. 경계 마커라는 단어 만 있으면됩니다 \b.

var str = 'hilly';
var value = str.includes('hi'); //true, even though the word 'hi' isn't found
var value = /\bhi\b/.test(str); //false - 'hi' appears but not as its own word


답변

다음과 같이 할 수도 있습니다.

const str = "hi, there"

const res = str.includes("hello") || str.includes("hi") || str.includes('howdy');

console.log(res);

포함 중 하나가 true를 반환 할 때마다 값은 true가되고, 그렇지 않으면 false가됩니다. 이것은 ES6에서 완벽하게 작동합니다.


답변

Array 및 RegEx의 일부 / 모든 방법을 사용하여 수행 할 수 있습니다 .

list (array)의 모든 단어가 문자열에 있는지 확인하려면 :

const multiSearchAnd = (text, searchWords) => (
  searchWords.every((el) => {
    return text.match(new RegExp(el,"i"))
  })
)

multiSearchAnd("Chelsey Dietrich Engineer 2018-12-11 Hire", ["cle", "hire"]) //returns false
multiSearchAnd("Chelsey Dietrich Engineer 2018-12-11 Hire", ["che", "hire"]) //returns true

여부를 확인하려면 모든 단어의 목록에서 (배열) 문자열에 존재 :

const multiSearchOr = (text, searchWords) => (
  searchWords.some((el) => {
    return text.match(new RegExp(el,"i"))
  })
)

multiSearchOr("Chelsey Dietrich Engineer 2018-12-11 Hire", ["che", "hire"]) //returns true
multiSearchOr("Chelsey Dietrich Engineer 2018-12-11 Hire", ["aaa", "hire"]) //returns true
multiSearchOr("Chelsey Dietrich Engineer 2018-12-11 Hire", ["che", "zzzz"]) //returns true
multiSearchOr("Chelsey Dietrich Engineer 2018-12-11 Hire", ["aaa", "1111"]) //returns false


답변

최선의 대답은 아니고 가장 깨끗한 것도 아니지만 더 관대하다고 생각합니다. 모든 검사에 동일한 필터를 사용하려는 경우와 같습니다. 실제로 .filter()배열과 함께 작동하고 필터링 된 배열을 반환합니다 (더 사용하기 더 쉽습니다).

var str1 = 'hi, how do you do?';
var str2 = 'regular string';
var conditions = ["hello", "hi", "howdy"];

// Solve the problem
var res1 = [str1].filter(data => data.includes(conditions[0]) || data.includes(conditions[1]) || data.includes(conditions[2]));
var res2 = [str2].filter(data => data.includes(conditions[0]) || data.includes(conditions[1]) || data.includes(conditions[2]));

console.log(res1); // ["hi, how do you do?"]
console.log(res2); // []


// More useful in this case
var text = [str1, str2, "hello world"];

// Apply some filters on data
var res3 = text.filter(data => data.includes(conditions[0]) && data.includes(conditions[2]));
// You may use again the same filters for a different check
var res4 = text.filter(data => data.includes(conditions[0]) || data.includes(conditions[1]));

console.log(res3); // []
console.log(res4); // ["hi, how do you do?", "hello world"]


답변

다음은 논란이되는 옵션입니다.

String.prototype.includesOneOf = function(arrayOfStrings) {
  if(!Array.isArray(arrayOfStrings)) {
    throw new Error('includesOneOf only accepts an array')
  }
  return arrayOfStrings.some(str => this.includes(str))
}

다음과 같은 작업을 수행 할 수 있습니다.

'Hi, hope you like this option'.toLowerCase().includesOneOf(["hello", "hi", "howdy"]) // True