Javascript中实现String.startsWith和endsWith方法

前端技术 2023/09/05 JavaScript

在操作字符串(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的优势是它不用复制字符串,直接扫描即可,所以效率更高。

本文地址:https://www.stayed.cn/item/13000

转载请注明出处。

本站部分内容来源于网络,如侵犯到您的权益,请 联系我

我的博客

人生若只如初见,何事秋风悲画扇。