This article mainly introduces the implementation of String in Javascript. startsWith and endsWith methods. These two easy-to-use methods are not available in JS. In this article, we have implemented these two methods by ourselves. If you need them, refer to the operation String (String) startsWith (anotherString) and endsWith (anotherString) are very easy to use. StartsWith determines whether the current string starts with anotherString, while 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
But unfortunately, Javascript does not contain these two methods, and you can only write them by yourself if necessary. Of course, it is not difficult to write it.
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 (). It obtains a substring. However, it is evaluated that slice is more efficient. The reason that indexOf () is not used here is that indexOf will scan the entire string. If the string is long, indexOf will be inefficient.
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 is more efficient than slice because it does not need to copy the string and scan it directly.