Javascript中的String.format方法实现

<script type='text/javascript'>

String.format = function() {
var s = arguments[0];
for (var i = 0; i < arguments.length - 1; i++) {
var reg = new RegExp("\\{" + i + "\\}", "gm");
s = s.replace(reg, arguments[i + 1]);
}
return s;
}

function stringFormat() {
var s = arguments[0];
for (var i = 0; i < arguments.length - 1; i++) {
var reg = new RegExp("\\{" + i + "\\}", "gm");
s = s.replace(reg, arguments[i + 1]);
}
return s;
}

--用法

var name='jeff';
var greeting1 = String.format("Hi--1, {0}, '{1}',this is a '{0}'! ", name, 'uuu');
var greeting2 = stringFormat("Hi--2, {0}, '{1}',this is a '{0}'! ", name, 'uuu');
alert(greeting1 + '\r\n' + greeting2);
</script>

上一篇:用树莓派开Wifi热点


下一篇:Java String.Format() 方法及参数说明