[javascript] JavaScript에서 문자열에 하위 문자열이 포함되어 있는지 확인하는 방법은 무엇입니까?

일반적으로 String.contains()방법 을 기대 하지만 방법이없는 것 같습니다.

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



답변

ECMAScript 6 소개 String.prototype.includes:

const string = "foo";
const substring = "oo";

console.log(string.includes(substring));

includes 그러나 Internet Explorer는 지원하지 않습니다 . ECMAScript 5 또는 이전 환경에서는을 사용 String.prototype.indexOf하여 하위 문자열을 찾을 수없는 경우 -1을 반환합니다.

var string = "foo";
var substring = "oo";

console.log(string.indexOf(substring) !== -1);


답변

있다 String.prototype.includesES6에서 :

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

이 점에 유의 Internet Explorer 또는 다른 오래된 브라우저에서 작동하지 않습니다 없거나 불완전한 ES6 지원. 오래된 브라우저에서 작동하게하려면 Babel 과 같은 트랜스 필러 , es6-shim 과 같은 shim 라이브러리 또는 MDN 의이 polyfill을 사용할 수 있습니다 .

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 알고리즘 검색 m 길이 -의 서브 스트링 n 개의 스트링 최악 O에서 ( N + m O (의 최악의 경우에 비해) 시간, Nm 순진한 알고리즘)는 그렇게 할 수있다 KMP를 사용 최악의 시간 복잡성을 염려한다면 합리적입니다.

https://www.nayuki.io/res/knuth-morris-pratt-string-matching/kmp-string-matcher.js 에서 가져온 Project Nayuki의 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.

function kmpSearch(pattern, text) {
  if (pattern.length == 0)
    return 0; // Immediate match

  // Compute longest suffix-prefix table
  var lsp = [0]; // Base case
  for (var i = 1; i < pattern.length; i++) {
    var j = lsp[i - 1]; // Start by assuming we're extending the previous LSP
    while (j > 0 && pattern.charAt(i) != pattern.charAt(j))
      j = lsp[j - 1];
    if (pattern.charAt(i) == pattern.charAt(j))
      j++;
    lsp.push(j);
  }

  // Walk through text string
  var j = 0; // Number of chars matched in pattern
  for (var i = 0; i < text.length; i++) {
    while (j > 0 && text.charAt(i) != pattern.charAt(j))
      j = lsp[j - 1]; // Fall back in the pattern
    if (text.charAt(i) == pattern.charAt(j)) {
      j++; // Next char matched, increment position
      if (j == pattern.length)
        return i - (j - 1);
    }
  }
  return -1; // Not found
}

console.log(kmpSearch('ays', 'haystack') != -1) // true
console.log(kmpSearch('asdf', 'haystack') != -1) // false


답변