StartsWith (anotherstring) and EndsWith (anotherstring) are very handy ways to manipulate string types. Where StartsWith determines whether the current string starts with anotherstring, and endswith 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 have these two methods, you need to write their own. Of course it's not hard to write.
if (typeof String.prototype.startsWith!= ' function ') {
String.prototype.startsWith = function (prefix) {
Return This.slice (0, prefix.length) = = prefix;}
String.slice () and string.substring () are similar to each other, but the evaluation says slice is more efficient. The reason for not using indexof () is that indexof scans the entire string, and if the string is long, the indexof is 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 scans only the last segment of the string, and the advantage of slice is that it does not have to copy the string to scan it directly, so it's more efficient.