如何在JavaScript中检查字符串是否包含子字符串?
通常我希望有一个如何在JavaScript中检查字符串是否包含子字符串?,javascript,string,substring,string-matching,Javascript,String,Substring,String Matching,通常我希望有一个String.contains()方法,但似乎没有 什么是检查此问题的合理方法?介绍了ECMAScript 6: const string=“foo”; const substring=“oo”; log(string.includes(substring)): 请注意,这是因为没有或不完整的ES6支持。要使其在旧浏览器中工作,您可能希望使用transpiler(如transpiler)、shim library(如shim library)或以下各项: 另一种选择是(克努特-
String.contains()
方法,但似乎没有
什么是检查此问题的合理方法?介绍了ECMAScript 6:
const string=“foo”;
const substring=“oo”;
log(string.includes(substring))代码>:
请注意,这是因为没有或不完整的ES6支持。要使其在旧浏览器中工作,您可能希望使用transpiler(如transpiler)、shim library(如shim library)或以下各项:
另一种选择是(克努特-莫里斯-普拉特)
KMP算法在最坏情况下的O(n+m)时间内搜索长度为n的字符串中的长度为m的子字符串,而在最坏情况下的O(n)时间内搜索长度为n的字符串⋅m) 对于naive算法,如果您关心最坏情况下的时间复杂度,那么使用KMP可能是合理的
以下是Nayuki项目的JavaScript实现,摘自:
函数kmpSearch(模式、文本){
if(pattern.length==0)
返回0;//立即匹配
//计算最长后缀前缀表
var lsp=[0];//基本大小写
对于(变量i=1;i0&&pattern.charAt(i)!=pattern.charAt(j))
j=lsp[j-1];
if(pattern.charAt(i)=pattern.charAt(j))
j++;
lsp.push(j);
}
//遍历文本字符串
var j=0;//模式中匹配的字符数
对于(变量i=0;i0&&text.charAt(i)!=pattern.charAt(j))
j=lsp[j-1];//在模式中后退
if(text.charAt(i)=pattern.charAt(j)){
j++;//下一个匹配字符,递增位置
if(j==模式长度)
返回i-(j-1);
}
}
return-1;//找不到
}
console.log(kmpSearch('ays','haystack')!=-1)//true
log(kmpSearch('asdf','haystack')!=-1)//false
只是好奇,为什么需要检查长度?IE在这种情况下会失败吗?同样,检查编号
也会像包括
一样失败。示例:es6 includes为“abc”返回false。includes(“ab”,“1”)
此polyfill将返回true
"potato".includes("to");
> true
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;
}
};
}
// 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.