我有一个数组 - 我想合并并用第2,第3个元素的值替换'%'
Array看起来像这样
[0] = "Hi may name is '%s' and my brother is '%d'"
[1] = "John"
[2] = "David"
我想返回一个字符串,如: “我的名字是约翰,我的兄弟是大卫”
有什么想法吗?提前谢谢
答案 0 :(得分:0)
好的,这样可行:http://jsfiddle.net/4ax7mvL4/5/
var a = [];
a[0] = "Hi may name is '%s' and my brother is '%d'";
a[1] = "John";
a[2] = "David";
var final = a[0];
for(var i = 1; i < a.length; i++) {
final = final.replace(/%[sd]/, a[i]);
}
alert(final);
但我确信那里有人可以优化它并让它更好看:)
答案 1 :(得分:0)
如果您在JavaScript中寻找C风格的printf
实现,可以尝试使用sprintf for JavaScript文档:
它的原型:
string sprintf(string format , [mixed arg1 [, mixed arg2 [ ,...]]])
类型说明符,可以是以下任何一种:
vsprintf
版本也接受数组形式的输入:
vsprintf("Hi may name is '%s' and my brother is '%d'", ["John", "David"]);
答案 2 :(得分:0)
把它放在&lt; head&gt;中标签
<script>
$(function() {
var arr = [
"Hi may name is '%s' and my brother is '%d'",
"John",
"David" ];
var txt = arr[0].replace("%s", arr[1]).replace("%d", arr[2]);
alert(txt);
});
</script>