JS expands the String. prototype. format String concatenation function,

Source: Internet
Author: User

JS expands the String. prototype. format String concatenation function,

1. concepts: the String. prototype attribute indicates the String prototype object. All String instances inherit from String. prototype. Any changes to String. prototype will affect all String instances.

2. In the above text, js expands the String. prototype. format String concatenation function. The first is the transformation of basic functions:

String.prototype.format = function(){  if(arguments.length==0){    return this;  }  for(var s=this, i=0; i<arguments.length; i++){    s = s.replace(new RegExp("\\{"+i+"\\}","g"), arguments[i]);  }  return s;};

3. The call method is as follows:

// Method 1var test = 'my {0} is {1} '; var result = test. format ('id', 'city light'); // method 2var test = 'my {name1} is {name2} '; var result = test. format ({name1: 'id', name2: 'city light '});

4. This is simple, with an extension of trim ()

String. prototype. trim = function () {return this. replace (/(^ \ s *) | (\ s * $)/g, "") ;}; String. prototype. ltrim = function () {return this. replace (/(^ \ s *)/g, "") ;}; String. prototype. rtrim = function () {return this. replace (/(\ s * $)/g, "") ;}; // call method var eg1 =1 ('# id '). val (). trim ();

Summary

The above is the JS extension String introduced by xiaobian. prototype. the format String concatenation function is helpful to you. If you have any questions, please leave a message and the editor will reply to you in time. Thank you very much for your support for the help House website!

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.