写一个简单的stringFormat来给自己用
function stringFormat(format, args) { var formatData; if (arguments.length == 2 && args && typeof(args) == "object") { formatData = args; } else { formatData = Array.prototype.slice.call(arguments, 1); } var pattern = []; for (var key in formatData) { pattern.push("\\{" + key + "\\}"); } if (!pattern.length) { return format; } pattern = pattern.join("|"); return format.replace(new RegExp(pattern, "img"), function(matchValue, index, inputString) { var key = matchValue.slice(1, -1); return formatData[key]; }); }
做些修改,让代码更短一些
function stringFormat() { var data, args = arguments, arr = [], i = 0; data = (args.length == 2 && args[1] && typeof(args[1]) == "object") ? args[1] : Array.prototype.slice.call(args, 1); for (arr[i++] in data); return arr.length ? args[0].replace(new RegExp("\\{" + arr.join("\\}|\\{") + "\\}", "img"), function(val) { return data[val.slice(1, -1)]; }) : args[0]; }
压缩
function stringFormat(){var e,t=arguments,n=[],r=0;e=t.length==2&&t[1]&&typeof t[1]=="object"?t[1]:Array.prototype.slice.call(t,1);for(n[r++]in e);return n.length?t[0].replace(new RegExp("\\{"+n.join("\\}|\\{")+"\\}","img"),function(t){return e[t.slice(1,-1)]}):t[0]}
示例1
stringFormat(); // undefined stringFormat("1 {0} 3 {1}"); //"1 {0} 3 {1}" stringFormat("1 {0} 3 {1}", 2); //"1 2 3 {1}" stringFormat("1 {0} 3 {1}", 2, 4); //"1 2 3 4" stringFormat("1 {0} 3 {1}", [2, 4]); //"1 2 3 4" stringFormat("1 {0} 3 {1}", [2]); //"1 2 3 {1}" stringFormat("1 {a} 3 {b}", { a: 2, b: 4}); //"1 2 3 4" stringFormat("1 {a} 3 {b}", { a: 2}); //"1 2 3 {b}" stringFormat("1 {a} 3 {b}", { a: 2, b: 4},1, 2); //"1 {a} 3 {b}" stringFormat("1 {0} 3 {1}", [2, 4], 4, 5); //"1 2,4 3 4" ``` ##示例2 ``` //多行的写法 加 ‘\‘ var mLine = "My name is {name},I am {age}. My name is {name},I am {age}. My name is {name},I am {age}."; stringFormat(mLine, { name: ‘lranye‘, age: 12}); /*结果: My name is lranye, I am 12.My name is lranye, I am 12.My name is lranye, I am 12. */ //执行: stringFormat(mLine, { name: ‘{age}‘, age: 12}); /*结果: My name is { age}, I am 12.My name is {age}, I am 12.My name is { age}, I am 12. */
注意在
javascript字符串中要表示斜杠‘\‘, 则要用转义符‘\‘ 写成 ‘\\‘
比如 ‘\‘ 对应要写成 ‘\\‘, ‘\\‘ 对应要写成‘\\\\‘
如果如下声明并赋值一个变量str
var str="1\2\3\4";
实际上 str值为"1234"
正确的表示方式为str="1\\2\\3\\4"
时间: 2024-10-10 03:00:23