有序的格式化文本,使用{number}做为占位符 通常使用:format("this is {0} for {1}", "a", "b") =》 this is a for b
形参:
pattern – 文本格式 arguments – 参数
返回值:
格式化后的文本
/** * 设置字符串format函数 * 例子: '你好, {0}, 我是{1}'.format('世界','张三') 效果 你好,世界,我是张三 */ String.prototype['format'] = function () { const e = arguments; return !!this && this.replace(/\{(\d+)\}/g, function (t, r) { return e[r] ? e[r] : t; }); };格式化文本,使用 {varName} 占位 map = {a: "aValue", b: "bValue"} format("{a} and {b}", map) ---=》 aValue and bValue
形参:
template – 文本模板,被替换的部分用 {key} 表示 map – 参数值对 ignoreNull – 是否忽略 null 值,忽略则 null 值对应的变量不被替换,否则替换为""
返回值:
格式化后的文本
/** * 格式化字符串 * @param 数值 * @param 类型 * map = {a: "aValue", b: "bValue"} format("{a} and {b}", map) ---=》 aValue and bValue * @returns {string} */ function format(template, map) { if(!template){ return '' } if(!map){ return template } for (let mapKey in map) { template = template.replaceAll('{' + mapKey + '}', map[mapKey]) } return template; }效果