Compile String. format () of javascript and Jquery ();

Source: Internet
Author: User

In javascript and Jquery, there seems to be no String. format (); this function, so we are very hard when splicing strings, for fear of making mistakes and chaos, so we can write a function instead.

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 ;}; // var a = "I like to eat {0} and {1 }, but the most favorite is {0}, and occasionally buy {2} "; // alert (String. format (a, "apple", "banana", "xiangli"); // result: I like to eat apples and bananas, but I like apples most, occasionally buy Pear

It starts with 0 digits.

We recommend that you write these items into a js file and call them each time.

 

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.