如何在JavaScript中檢查字符串是否包含子字符串?

How to check whether a string contains a substring in JavaScript?
投票:7430回答:3

通常我希望使用String.contains()方法,但是似乎沒有。

有什麼合理的方法來檢查?

tags:javascript,string,substring,string-matching
3回答
500
投票

ES6中有一個String.prototype.includes

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

請注意,這在Internet Explorer或其他不支持ES6或不完全支持ES6的舊瀏覽器中不起作用 為了使其在舊的瀏覽器中運行,您可能希望使用像Babel這樣的編譯器 ,像es6-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;
    }
  };
}

13294
投票

ECMAScript 6引入了String.prototype.includes

 var string = "foo", substring = "oo"; console.log(string.includes(substring)); 

includes 不支持Internet Explorer 在ECMAScript 5或更舊的環境中,使用String.prototype.indexOf ,如果找不到子字符串,則返回-1:

 var string = "foo", substring = "oo"; console.log(string.indexOf(substring) !== -1); 


22
投票

另一種選擇是KMP (Knuth–Morris–Pratt)。

對於長度- 的長度- ñ字符串的子串在最壞情況下的O(N + M)時,相對於為O(n⋅ )為幼稚算法的最壞情況的KMP算法搜索,因此使用KMP可以是如果您擔心最壞的情況下的時間複雜性,則為合理

這是Nayuki項目的JavaScript實現,取自https://www.nayuki.io/res/knuth-morris-pratt-string-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 } console.log(kmpSearch('ays', 'haystack') != -1) // true console.log(kmpSearch('asdf', 'haystack') != -1) // false 


©2020 sofbug.com - All rights reserved.