在Javascript里通过原型扩展和正则表达式实现类似于C#里的String.Format方法.
方法实现:
String.prototype.format = function (args) {
var str = this;
return str.replace(new RegExp("{-?[0-9]+}", "g"), function(item) {
var intVal = parseInt(item.substring(1, item.length - 1));
var replace;
if (intVal >= 0) {
replace = args[intVal];
} else if (intVal === -1) {
replace = "{";
} else if (intVal === -2) {
replace = "}";
} else {
replace = "";
}
return replace;
});
};
var str = this;
return str.replace(new RegExp("{-?[0-9]+}", "g"), function(item) {
var intVal = parseInt(item.substring(1, item.length - 1));
var replace;
if (intVal >= 0) {
replace = args[intVal];
} else if (intVal === -1) {
replace = "{";
} else if (intVal === -2) {
replace = "}";
} else {
replace = "";
}
return replace;
});
};
使用如下:
var str = "She {1} {0}{2} by the {0}{3}. {-1}^_^{-2}";
str = str.format(["sea", "sells", "shells", "shore"]);
alert(str);//out put: She sells seashells by the seashore. {^_^}
str = str.format(["sea", "sells", "shells", "shore"]);
alert(str);//out put: She sells seashells by the seashore. {^_^}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步