<html>
<head>
<title>JavaScript String.Format</title>
<script type="text/javascript">
// This is the function.
String.prototype.format = function (args) {
var str = this;
return str.replace(String.prototype.format.regex, 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;
});
};
String.prototype.format.regex = new RegExp("{-?[0-9]+}", "g");
// Sample usage.
var str = "She {1} {0}{2} by the {0}{3}. {-1}^_^{-2}";
str = str.format(["sea", "sells", "shells", "shore"]);
alert(str);
</script>
</head>
</html>String.Format in JavaScript
最新推荐文章于 2024-01-18 17:18:46 发布
本文介绍了一种在JavaScript中实现字符串格式化的自定义方法。通过扩展String.prototype,该方法允许开发者使用类似C#中的String.Format的功能,即在字符串中预留占位符并在运行时用变量值替换这些占位符。
1810

被折叠的 条评论
为什么被折叠?



