String. startsWith and endsWith in Javascript _ javascript skills

Source: Internet
Author: User
This article mainly introduces the implementation of String in Javascript. startsWith and endsWith methods. These two easy-to-use methods are not available in JS. In this article, we have implemented these two methods by ourselves. If you need them, refer to the operation String (String) startsWith (anotherString) and endsWith (anotherString) are very easy to use. StartsWith determines whether the current string starts with anotherString, while 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

But unfortunately, Javascript does not contain these two methods, and you can only write them by yourself if necessary. Of course, it is not difficult to write it.

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

String. slice () is similar to String. substring (). It obtains a substring. However, it is evaluated that slice is more efficient. The reason that indexOf () is not used here is that indexOf will scan the entire string. If the string is long, indexOf will be inefficient.

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

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.