When operating on the String type, startsWith(anotherString) and endsWith(anotherString) are very useful methods. Among them, startsWith determines whether the current string starts with anotherString, and endsWith determines whether it ends. Example:
"abcd".startsWith("ab"); // true "abcd".startsWith("bc"); // false "abcd".endsWith("cd"); // true "abcd".endsWith("e"); // false "a".startsWith("a"); // true "a".endsWith("a"); // true
Unfortunately, Javascript does not come with these two methods, so you can only write them yourself if necessary. Of course it’s not difficult to write.
if (typeof String.prototype.startsWith != 'function') { String.prototype.startsWith = function (prefix){ return this.slice(0, prefix.length) === prefix; }; }
String.slice() is similar to String.substring() in that they both obtain a substring, but some reviews say that slice is more efficient. The reason why indexOf() is not used here is that indexOf will scan the entire string. If the string is very long, the efficiency of indexOf will be very poor.
if (typeof String.prototype.endsWith != 'function') { String.prototype.endsWith = function(suffix) { return this.indexOf(suffix, this.length - suffix.length) !== -1; }; }
Unlike startsWith, indexOf can be used in endsWith. The reason is that it only scans the last string, and the advantage over slice is that it does not need to copy the string, just scan it directly, so it is more efficient.