在Javascript中使用String.startsWith和endsWith
在操作字符串(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的效率就會很差。
1 if (typeof String.prototype.endsWith != 'function') { 2 String.prototype.endsWith = function(suffix) { 3 return this.indexOf(suffix, this.length - suffix.length) !== -1; 4 }; 5 }
和startsWith不一樣,endsWith中可以使用indexOf。原因是它只掃描了最后的一段字符串,而比起slice的優勢是它不用復制字符串,直接掃描即可,所以效率更高。