Three js methods to implement the string substring method, stringsubstring

Source: Internet
Author: User

Three js methods to implement the string substring method, stringsubstring

Recently, I encountered a question: "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<endIndex;i++){    newArr.push(str.charAt(i));  }  return newArr.join("");}//test"Hello world!".mysubstring(3);//"lo world!""Hello world!".mysubstring(3,7);//"lo w"

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<beginIndex;i++){    beginArr.push(str.charAt(i));  }  for(var i=endIndex;i<str.length;i++){    endArr.push(str.charAt(i));  }  return str.replace(beginArr.join(""),"").replace(endArr.join(""),"");}//testconsole.log("Hello world!".mysubstring(3));//"lo world!"console.log("Hello world!".mysubstring(3,7));//"lo w"

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.