_javascript techniques for implementing String.startswith and EndsWith methods in JavaScript

Source: Internet
Author: User

StartsWith (anotherstring) and EndsWith (anotherstring) are very handy ways to manipulate string types. Where StartsWith determines whether the current string starts with anotherstring, and endswith 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

Unfortunately, JavaScript does not have these two methods, you need to write their own. Of course it's not hard to write.

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

String.slice () and string.substring () are similar to each other, but the evaluation says slice is more efficient. The reason for not using indexof () is that indexof scans the entire string, and if the string is long, the indexof is 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 scans only the last segment of the string, and the advantage of slice is that it does not have to copy the string to scan it directly, so it's more efficient.

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.