var str1 = " Your String Value Here.!! "; // Starts & ends with spacesif (str1.startsWith("Your")) { } // returns FALSE due to the leading spaces…if (str1.endsWith("Here.!!")) { } // returns FALSE due to trailing spaces…
var str2 = str1.trim(); // Removes all spaces (and other white-space) from start and end of `str1`.if (str2.startsWith("Your")) { } // returns TRUEif (str2.endsWith("Here.!!")) { } // returns TRUE
function startsWith(s,starter) {for (var i = 0,cur_c; i < starter.length; i++) {cur_c = starter[i];if (s[i] !== starter[i]) {return false;}}return true;}
I haven't come across the last solution which makes uses of a loop. Surprisingly this solution outperforms the first 3 by a significant margin. Here is the jsperf test I performed to reach this conclusion: http://jsperf.com/startswith2/2
Peace
ps: ecmascript 6 (harmony) introduces a native startsWith method for strings. Just think how much time would have been saved if they had thought of including this much needed method in the initial version itself.
Update
As Steve pointed out (the first comment on this answer), the above custom function will throw an error if the given prefix is shorter than the whole string. He has fixed that and added a loop optimization which can be viewed at http://jsperf.com/startswith2/4.
Note that there are 2 loop optimizations which Steve included, the first of the two showed better performance, thus I will post that code below:
function startsWith2(str, prefix) {if (str.length < prefix.length)return false;for (var i = prefix.length - 1; (i >= 0) && (str[i] === prefix[i]); --i)continue;return i < 0;}
false results from fastest to slowest avg:1) "{\"label\":\"slice\",\"avg\":0.0362}"2) "{\"label\":\"startsWith\",\"avg\":0.1141}"3) "{\"label\":\"lastIndexOf\",\"avg\":0.11512}"4) "{\"label\":\"substring\",\"avg\":0.14751}"5) "{\"label\":\"indexOf\",\"avg\":0.23109}"
true results from fastest to slowest avg:1) "{\"label\":\"startsWith\",\"avg\":0.11207}"2) "{\"label\":\"lastIndexOf\",\"avg\":0.12196}"3) "{\"label\":\"substring\",\"avg\":0.12495}"4) "{\"label\":\"indexOf\",\"avg\":0.33667}"5) "{\"label\":\"slice\",\"avg\":0.49923}"
Opera 62(substring获胜。结果与Chrome相似,我并不感到惊讶,因为Opera基于Chromium和Blink):
false results from fastest to slowest avg:{"label":"substring","avg":0.09321}{"label":"slice","avg":0.09463}{"label":"lastIndexOf","avg":0.95347}{"label":"indexOf","avg":1.6337}{"label":"startsWith","avg":3.61454}
true results from fastest to slowest avg:1) {"label":"substring","avg":0.08855}2) {"label":"slice","avg":0.12227}3) {"label":"indexOf","avg":0.79914}4) {"label":"lastIndexOf","avg":1.05086}5) {"label":"startsWith","avg":3.70808}