Home > Web Front-end > JS Tutorial > body text

Javascript中实现String.startsWith和endsWith方法_javascript技巧

WBOY
Release: 2016-05-16 15:56:20
Original
1513 people have browsed it

在操作字符串(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
Copy after login

但不幸的是,Javascript中没有自带这两个方法,需要的话只能自己写。当然写起来也不难就是了。

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

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;
 };
}
Copy after login

和startsWith不一样,endsWith中可以使用indexOf。原因是它只扫描了最后的一段字符串,而比起slice的优势是它不用复制字符串,直接扫描即可,所以效率更高。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!