StringUtil

String.format

 /**
     * Allows you to define a tokenized string and pass an arbitrary number of arguments to replace the tokens.  Each
     * token must be unique, and must increment in the format {0}, {1}, etc.  Example usage:
     * <pre><code>
var cls = 'my-class', text = 'Some text';
var s = String.format('&lt;div class="{0}">{1}&lt;/div>', cls, text);
// s now contains the string: '&lt;div class="my-class">Some text&lt;/div>'
     * </code></pre>
     * @param {String} string The tokenized string to be formatted
     * @param {String} value1 The value to replace token {0}
     * @param {String} value2 Etc...
     * @return {String} The formatted string
     * @static
     */

// Ext的实现方法:
Ext.applyIf(String, {
    format : function(format){
        var args = Ext.toArray(arguments, 1);
        
        // m:匹配的值,i匹配的项index   return 替换m的值
        return format.replace(/\{(\d+)\}/g, function(m, i){
            return args[i];
        });
    }
});

// 通常的实现方法
String.format = function() {
	var s = arguments[0];
	for (var i = 0; i < arguments.length - 1; i++) {
	    var reg = new RegExp("\\{" + i + "\\}", "gm");
	    s = s.replace(reg, arguments[i + 1]);
	}
	return s;
}

你可能感兴趣的:(String)