我有字符串(长度50-2000)和潜在子字符串(长度2-8),它们只能在特定位置开始(它可能出现在其他地方,但我不在乎)。我需要测试大量的字符串,所以速度是关键。有没有更快的方法:
var q = baseString.indexOf(searchString, assumedIndex) === assumedIndex; 或
var q = baseString.substr(assumedIndex, searchString.length) === searchString; 发布于 2016-07-28 22:20:34
记住阿米特在评论中所说的话,我想我最好添加一个(可能)比substr方法更快的替代方法:
var q = baseString.startsWith(searchString, assumedIndex); 来自MDN
startsWith()方法确定一个字符串是否以另一个字符串的字符开头,并根据需要返回true或false。
小示例:
> "Hello world!".startsWith("world!",6)
< true我认为它可能更快的原因是polyfill (如下所示)直接是您用substr实现的,除了浏览器实现将是本机实现的,并且可能没有字符串复制。所以它至少应该和你已经建议的一样快。
多边形填充:
if (!String.prototype.startsWith) {
String.prototype.startsWith = function(searchString, position){
position = position || 0;
return this.substr(position, searchString.length) === searchString;
};
}https://stackoverflow.com/questions/38573988
复制相似问题