3 Kinds of JS implement string substring method _javascript Skill

Source: Internet
Author: User

Recently encountered a topic, "How to use JavaScript to implement the string substring method?" "I now think of the following three kinds of options:
method One: Use Charat to remove the interception part:

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 Two: Converts a string into an array and then takes out 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 ("");

Test
console.log ("Hello world!"). Mysubstring (3));//"Lo world!"
Console.log ("Hello world!"). Mysubstring (3,7));//"Lo W"


method Three: Take out the tail part, and then remove the excess parts with replace, apply to beginindex small, string length-endindex small situation:

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 (""), "");

Test
console.log ("Hello world!"). Mysubstring (3));//"Lo world!"
Console.log ("Hello world!"). Mysubstring (3,7));//"Lo W"

The above 3 kinds of JS implement string substring method Everyone can try, compare which method is more convenient, I hope this article for everyone's learning help.

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.