Common javascript Functions

Source: Internet
Author: User

1. Extend the format function to the String prototype.

String.prototype.format = function () {        if (arguments.length == 0)            return null;        var str = arguments[0];        for (var i = 1; i < arguments.length; i++) {            var re = new RegExp('\\{' + (i - 1) + '\\}', 'gm');            str = str.replace(re, arguments[i]);        }        return str;    }

You can use it in the demo as follows:

<div id="div1"></div>
Window. onload = function () {var ss = "<strong> {0} </strong> is a boy and <strong> {1} </strong> is a girl. "; Document. getElementById (" div1 "). innerHTML = ss. format (ss," Small s "," Large s ");}

2. Use static methods

/*** Description: String Formatting Function String. format (arg0, arg1); arg0 is the String source * Author: ye minglong * Time: 2013/06/07 */String. format = function () {if (arguments. length = 0) return null; var str = arguments [0]; for (var I = 1; I <arguments. length; I ++) {var re = new RegExp ('\ {' + (I-1) + '\}', 'G'); str = str. replace (re, arguments [I]);} return str ;}

You can use it in the demo as follows:

<div id="div1"></div>
Window. onload = function () {var ss = "<strong> {0} </strong> is a boy and <strong> {1} </strong> is a girl. "; Document. getElementById (" div1 "). innerHTML = String. format (ss," Small s "," Large s ");}

 

/*** @ Trim (); remove the space function */String. prototype. trim = function () {// use a regular expression to replace the front and back spaces with empty strings. Return this. replace (/(^ \ s *) | (\ s * $)/g ,"");}

 

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.