Javascript中實現String.startsWith和endsWith方法_javascript技巧

來源:互聯網
上載者:User

在操作字串(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的效率就會很差。

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

和startsWith不一樣,endsWith中可以使用indexOf。原因是它只掃描了最後的一段字串,而比起slice的優勢是它不用複製字串,直接掃描即可,所以效率更高。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.