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

Implementing String.startsWith and endsWith methods in Javascript_javascript tips

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

When operating on the String type, startsWith(anotherString) and endsWith(anotherString) are very useful methods. Among them, startsWith determines whether the current string starts with anotherString, and endsWith determines whether it ends. Example:

"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

Unfortunately, Javascript does not come with these two methods, so you can only write them yourself if necessary. Of course it’s not difficult to write.

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

String.slice() is similar to String.substring() in that they both obtain a substring, but some reviews say that slice is more efficient. The reason why indexOf() is not used here is that indexOf will scan the entire string. If the string is very long, the efficiency of indexOf will be very poor.

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

Unlike startsWith, indexOf can be used in endsWith. The reason is that it only scans the last string, and the advantage over slice is that it does not need to copy the string, just scan it directly, so it is more efficient.

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