문자열에 자바 스크립트에 하위 문자열이 포함되어 있는지 확인하는 방법은 무엇입니까?


질문

 

일반적으로 String.Contains () 메서드를 기대하지만 하나가되는 것 같지 않습니다.

이것을 확인하는 합리적인 방법은 무엇입니까?


답변

 

ECMAScript 6은 String.prototype.inCludes를 소개했습니다.

const string = "foo"; const 하위 문자열 = "oo"; console.log (string.includes (하위 문자열));// 진실

포함하지 않지만 Internet Explorer 지원이 포함되어 있지 않습니다.ECMAScript 5 또는 이전 환경에서는 -1을 찾을 수 없을 때 -1을 반환하는 String.prototype.indexof를 사용합니다.

var string = "foo"; var substring = "oo"; console.log (string.indexof (substring)! == -1);// 진실



답변

ES6에는 String.prototype.inCludes가 있습니다.

"potato".includes("to");
> true

이것은 Internet Explorer 또는 No 또는 Imponplet ES6 지원이있는 다른 오래된 브라우저에서는 작동하지 않습니다.오래된 브라우저에서 작동하도록하려면 Babel과 같은 트랜스 필러, ES6 shim과 같은 심판 또는 MDN 에서이 폴리필을 사용하고자 할 수 있습니다.

if (!String.prototype.includes) {
  String.prototype.includes = function(search, start) {
    'use strict';
    if (typeof start !== 'number') {
      start = 0;
    }

    if (start + search.length > this.length) {
      return false;
    } else {
      return this.indexOf(search, start) !== -1;
    }
  };
}


답변

또 다른 대안은 KMP (Knuth-Morris-Pratt)입니다.

KMP 알고리즘은 순진한 알고리즘의 최악의 경우에 비해 최악의 경우 (N + M) 시간에 비해 LINGTE-N 스트링의 길이 -M 하위 문자열을 검색하여 KMP를 사용하여최악의 시간 복잡성을 신경 쓰는 경우 합리적이어야합니다.

다음은 https://www.nayuki.io/res/knuth-morris-pratt-string-matching/kmp-string-matcher.js에서 가져온 프로젝트 나이키의 JavaScript 구현입니다.

// Searches for the given pattern string in the given text string using the Knuth-Morris-Pratt string matching algorithm.
// If the pattern is found, this returns the index of the start of the earliest match in 'text'. Otherwise -1 is returned.

함수 KMPSearch (패턴, 텍스트) { if (pattern.length == 0) 반환 0; // 즉각적인 일치합니다 // 가장 긴 접미사 접두사 표를 계산합니다 var lsp = [0]; // 기본 케이스 for (var i = 1; i 0 && pattern.charrat (i)! = pattern.charat (j)) J = LSP [J - 1]; if (pattern.charat (i) == pattern.charat (j)) J ++; lsp.push (j); } // 텍스트 문자열을 걷습니다 var j = 0; // 무늬와 일치하는 문자 수입니다 for (var i = 0; i 0 && text.charrat (i)! = pattern.charat (j)) J = LSP [J - 1]; // 패턴으로 되돌아갑니다 if (text.charat (i) == pattern.charat (j)) { J ++; // 다음 char 일치, 증분 위치 if (j == pattern.length) 반환 - (j - 1); } } 반환 -1; // 찾을 수 없습니다 } console.log (kmpsearch ( 'ays', 'haystack')! = -1) // true console.log (kmpsearch ( 'asdf', 'haystack')! = -1) // false



답변

출처:https://stackoverflow.com/questions/1789945/how-to-check-whether-a-string-contains-a-substring-in-javascript