Three js methods to implement the string substring method _ javascript tips-js tutorial

Source: Internet
Author: User
This article mainly introduces three methods for implementing the string substring in javascript. If you need it, refer to a question recently asked: "How to use javascript to implement the string substring method ?" I have come up with the following three solutions:
Method 1: extract the captured part with charAt:

String. prototype. mysubstring = function (beginIndex, endIndex) {var str = this, newArr = []; if (! EndIndex) {endIndex = str. length;} for (var I = beginIndex; I
 
  

Method 2: Convert the string into an array and extract the required part:

String.prototype.mysubstring=function(beginIndex,endIndex){  var str=this,    strArr=str.split("");  if(!endIndex){    endIndex=str.length;  }  return strArr.slice(beginIndex,endIndex).join("");}//testconsole.log("Hello world!".mysubstring(3));//"lo world!"console.log("Hello world!".mysubstring(3,7));//"lo w"

Method 3: remove the header and tail parts, and use replace to remove the excess parts. This method is applicable when the beginIndex is small and the string length-endIndex is small:

String. prototype. mysubstring = function (beginIndex, endIndex) {var str = this, beginArr = [], endArr = []; if (! EndIndex) {endIndex = str. length;} for (var I = 0; I
   
    

You can try the above three js methods to implement the string substring method and compare which method is more convenient. I hope this article will be helpful for your learning.

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.