javascript - Fastest way to check if substring is at specific position of another string -
i have string (length 50-2000) , potential substring (length 2-8) can start @ specific position (it may occur elsewhere don't care). need test large number of strings speed key here. there faster way then:
var q = basestring.indexof(searchstring, assumedindex) === assumedindex;
or
var q = basestring.substr(assumedindex, searchstring.length) === searchstring;
keeping in mind amit said in comments, thought might add alternative (probably) faster @ least substr
method:
var q = basestring.startswith(searchstring, assumedindex);
from mdn:
the
startswith()
method determines whether string begins characters of string, returningtrue
orfalse
appropriate.
small example:
> "hello world!".startswith("world!",6) < true
the reason argue may faster because polyfill (shown below) directly implemented substr
, except browser implementations implemented natively , without string copying. should @ least fast suggested.
polyfill:
if (!string.prototype.startswith) { string.prototype.startswith = function(searchstring, position){ position = position || 0; return this.substr(position, searchstring.length) === searchstring; }; }
Comments
Post a Comment