在操作字符串(string)类型的时候,startswith(anotherstring)和endswith(anotherstring)是非常好用的方法。其中startswith判断当前字符串是否以anotherstring作为开头,而endswith则是判断是否作为结尾。举例:
"abcd".startsWith("ab"); // true
"abcd".startsWith("bc"); // false
"abcd".endsWith("cd"); // true
"abcd".endsWith("e"); // false
"a".startsWith("a"); // true
"a".endsWith("a"); // true
但不幸的是,Javascript中没有自带这两个方法,需要的话只能自己写。当然写起来也不难就是了。
if (typeof String.prototype.startsWith != 'function') {
String.prototype.startsWith = function (prefix){
return this.slice(0, prefix.length) === prefix;
};
}
String.slice()和String.substring()类似,都是获得一段子串,但有评测说slice的效率更高。这里不使用indexOf()的原因是,indexOf会扫描整个字符串,如果字符串很长,indexOf的效率就会很差。
立即学习“Java免费学习笔记(深入)”;
if (typeof String.prototype.endsWith != 'function') {
String.prototype.endsWith = function(suffix) {
return this.indexOf(suffix, this.length - suffix.length) !== -1;
};
}
和startsWith不一样,endsWith中可以使用indexOf。原因是它只扫描了最后的一段字符串,而比起slice的优势是它不用复制字符串,直接扫描即可,所以效率更高。











