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