DIV CSS 佈局教程網

為 String 補上 startsWith 與 endsWith
編輯:關於JavaScript     

處理字串時,startsWith(anotherString) 與 endsWith(anotherString) 是非常好用的判斷:前者檢查目前字串是否以 anotherString 開頭,後者檢查是否以其結尾。例如:

"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 早期並沒有內建這兩個方法,需要時只能自己補。寫起來倒是不難。

startsWith

if (typeof String.prototype.startsWith != 'function') {
  String.prototype.startsWith = function (prefix) {
    return this.slice(0, prefix.length) === prefix;
  };
}

這裡用 slice 而不是 indexOf,原因在效能。indexOf 會從頭掃描整個字串直到找到為止,字串很長時開銷可觀;而 slice 只截取 prefix.length 那麼短的頭部再直接比較,成本與 prefix 的長度有關,與原字串的長度無關。slice 與 substring 功能類似,但有實證顯示 slice 的實作效率較佳,因此優先採用。

endsWith

if (typeof String.prototype.endsWith != 'function') {
  String.prototype.endsWith = function (suffix) {
    return this.indexOf(suffix, this.length - suffix.length) !== -1;
  };
}

和 startsWith 不同,這裡反而用 indexOf 更好。因為起始位置已經被指定為「尾端往前推算 suffix 這麼長」的地方,搜尋範圍只剩最後一小段,不可能掃到全字串;而它相比 slice 的優勢是不必複製字串,直接在原地掃描,因此效率更高。

幾個實務提醒

第一,ES6 已經把 startsWith 與 endsWith 列入標準,現代瀏覽器全部支援。因此這段 polyfill 今天的用處只剩下支援舊版 IE,新專案可以直接用原生方法。

第二,原生的 startsWith 支援第二個參數作為起算位置,例如 "a-b-c".startsWith("b", 2) 會回傳 true。自己實作的版本沒有這個能力,遷移程式碼時要留意。

第三,擴充 String.prototype 會讓該型別的所有字串都多出可列舉屬性。若你的程式有用 for-in 走訪字串(少見但存在),可能出現預期外的行為。較保守的做法是改用獨立函式 function startsWith(str, prefix) { return str.slice(0, prefix.length) === prefix; },不污染原型。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved