epeli/underscore.string — Issue #86: startsWith and endsWith are too slow
Author: ajax333221
Created: 2012-02-26 18:44:27+00:00
State: open

I propose to change them to:

function strStarts(fnd,str,bol){
return str.lastIndexOf(fnd,0)==0;
}

function strEnds(fnd,str,bol){
var i=str.length-fnd.length;
return str.lastIndexOf(fnd,i)==i;
}

It will be way much faster.

It would also be interesting to add a new feature that allows to ignore-case. Something like:

function strStarts(fnd,str,bol){
return (bol?str.toLowerCase().lastIndexOf(fnd.toLowerCase(),0):str.lastIndexOf(fnd,0))==0;
}

function strEnds(fnd,str,bol){
var i=str.length-fnd.length;
return (bol?str.toLowerCase().lastIndexOf(fnd.toLowerCase(),i):str.lastIndexOf(fnd,i))==i;
}

I ran some tests, and even with the new feature is way much faster than the current method.

Thanks for your time