手机
当前位置:查字典教程网 >编程开发 >Javascript教程 >Javascript中实现String.startsWith和endsWith方法
Javascript中实现String.startsWith和endsWith方法
摘要:在操作字符串(String)类型的时候,startsWith(anotherString)和endsWith(anotherString)是...

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

【Javascript中实现String.startsWith和endsWith方法】相关文章:

JavaScript中string对象

javascript中clipboardData对象用法

JavaScript实现Iterator模式实例分析

Javascript中With语句用法实例

JavaScript基于setTimeout实现计数的方法

JavaScript中的anchor()方法使用详解

JavaScript中的sub()方法的使用介绍

Javascript中prototype属性实现给内置对象添加新的方法

javascript常用方法总结

纯javascript实现四方向文本无缝滚动效果

精品推荐
分类导航