转 用JS实现PHP的sprintf函数

时间:2022-10-29 20:48:01
函数如下:<script type="text/javascript">function sprintf(){    var arg = arguments,        str = arg[0] || '',        i, n;    for (i = 1, n = arg.length; i < n; i++) {        str = str.replace(/%s/, arg[i]);    }    return str;}</script> 第一个参数是包含的“%s”的字符串,其他参数是对应的用来替换“%s”的变量。如:<script type="text/javascript">var str = "床前%s明光,疑是%s上霜;举头%s明月,低头%s故乡。",    var1 = "明",    var2 = "地",    var3 = "望",     var4 = "思";str = sprintf(str, var1, var2, var3, var4);</script>