Source: http://www.cnblogs.com/nonlyli/archive/2008/08/14/1267480.html
經(jīng)常在js里拼字符串,實在忍不下去了,在網(wǎng)上搜索了一下js版的String.format。
第一個寫得太巧妙了,看了半天沒看懂。
為了跟C#語法配合,還是選用第二個版本吧。
看了下沒有在jquery里找到這方面的功能,也不知ASP.NET Ajax Library里是怎么實現(xiàn)這個的。
<script type="text/javascript">
//V1 method
String.prototype.format = function()
{
var args = arguments;
return this.replace(/\{(\d+)\}/g,
function(m,i){
return args[i];
});
}
//V2 static
String.format = function() {
if( arguments.length == 0 )
return null;
var str = arguments[0];
for(var i=1;i<arguments.length;i++) {
var re = new RegExp('\\{' + (i-1) + '\\}','gm');
str = str.replace(re, arguments[i]);
}
return str;
}
var a = "I Love {0}, and You Love {1},Where are {0}! {4}";
alert(String.format(a, "You","Me"));
alert(a.format("You","Me"));
</script>
來源參考:
V1:http://samlin.cnblogs.com/archive/2008/01/25/1053610.html
V2:http://www.cnblogs.com/hwade/articles/867767.html
String.replace的特殊用法:
http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:String:replace
String.replace的妙用:
http://www.codebit.cn/pub/html/javascript/tip/javascript_replace/