Formatting of JavaScript strings

Source: Internet
Author: User

formatting strings
String.prototype.format = function (args) {    var result = this;    if (Arguments.length < 1) {        return result;    }    var data = arguments;       If the template parameter is an array if    (arguments.length = = 1 && typeof (args) = = "Object") {        //If the template parameter is Object        data = args;    } For    (var key in data) {        var value = Data[key];        if (undefined! = value) {            result = Result.replace ("{" + key + "}", value);}        }    return result;}
How to use:
Two ways to call Var template1= "I am {0}, this year {1}"; var Result1=template1.format ("Loogn"); var template2= "I am {name}, this year {age}"; var Result2=template2.format ({name: "Loogn", age:22});//Two results are "I'm Loogn, 22 this year."

Reference: http://www.cnblogs.com/yelaiju/archive/2012/03/27/2419212.html

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.