String.Format in JavaScript

来源:互联网 发布:复共轭矩阵与厄米矩阵 编辑:程序博客网 时间:2024/04/30 14:41
<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>

0 0
原创粉丝点击