1 /** 2 * 对目标字符串进行格式化 3 * @constructor 4 * @name vui.format 5 * @author putaoshu@126.com 6 * @date 2013-4-4 7 * @param {String} source 目标字符串 8 * @param {Object} opts 组件配置 9 * @returns {String} 格式化后的字符串 10 * @example 11 vui.format('<div class="#{myClassName}"></div>',{myClassName:'menu'}) 12 */ 13 14 vui.format = function (source, opts) { 15 source = String(source); 16 var data = Array.prototype.slice.call(arguments,1), toString = Object.prototype.toString; 17 if(data.length){ 18 data = data.length == 1 ? 19 /* ie 下 Object.prototype.toString.call(null) == '[object Object]' */ 20 (opts !== null && (/\[object Array\]|\[object Object\]/.test(toString.call(opts))) ? opts : data) 21 : data; 22 return source.replace(/#\{(.+?)\}/g, function (match, key){ 23 var replacer = data[key]; 24 // chrome 下 typeof /a/ == 'function' 25 if('[object Function]' == toString.call(replacer)){ 26 replacer = replacer(key); 27 } 28 return ('undefined' == typeof replacer ? '' : replacer); 29 }); 30 } 31 return source; 32 } 33 34