보통 나는 String.contains()
메쏘드를 기대할 것입니다, 그러나 하나 인 것 같지 않습니다.
이것을 확인하는 합리적인 방법은 무엇입니까?
ES6 도입 String.prototype.includes
:
var string = "foo",
substring = "oo";
string.includes(substring)
includes
IE support 가 없습니다. ES5 또는 이전 환경에서 하위 문자열을 찾지 못하면 -1을 반환하는 String.prototype.indexOf
대신 다음을 사용할 수 있습니다.
var string = "foo",
substring = "oo";
string.indexOf(substring) !== -1
ES6에 String.prototype.includes
가 있음) :
"potato".includes("to");
> true
이 Internet Explorer 또는 다른 오래된 브라우저 / ES6 지원이 없거나 불완전한 경우에는 작동하지 않습니다.) 오래된 브라우저에서 작동되게하려면 Babel , shim 라이브러리 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 입니다.
KMP 알고리즘은 최악의 경우 선형 시간 문자열 검색을 제공하므로 최악의 시간 복잡도에 신경 쓰면 합리적인 방법입니다.
다음은 Project Nayuki의 JavaScript 구현입니다. https://www.nayuki.io/res/knuth-morris-prattstring-matching/kmp-string-matcher.js :
// 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
}
사용 예 :
kmpSearch('ays', 'haystack') != -1 // true
kmpSearch('asdf', 'haystack') != -1 // false