如何将数组的数组和索引替换为字符串?

时间:2017-12-04 18:49:24

标签: javascript arrays

考虑

var arr = ["a","b","c"];
var string = "Hello {1} is a friend of {2} and {3}";

所以将{1}替换为"a"{2}替换为"b",将{3}替换为"c"

我们如何使用JavaScript?

3 个答案:

答案 0 :(得分:3)

您可以通过减少数组和替换字符串来实现此目的。



var arr = ["a","b","c"];
var s = "Hello {1} is a friend of {2} and {3}";

var result = arr.reduce((str, replacement, idx) => {
  return str.replace(`{${idx + 1}}`, replacement)
}, s);

console.log(result);




答案 1 :(得分:2)

您正在寻找ES6中的template strings

const arr = ['a', 'b', 'c'];

const string = `Hello ${arr[0]} is a friend of ${arr[1]} and ${arr[2]}`;

添加一些destructuring

const [
  a,
  b
  c,
] = ['a', 'b', 'c'];

const string = `Hello ${a} is a friend of ${b} and ${c}`;

ES5中的@EDIT,旧的

var arr = ['a', 'b', 'c'];

var string = 'Hello ' + arr[0] + ' is a friend of ' + arr[1] + ' and ' + arr[2];

enter image description here

答案 2 :(得分:0)

您可以使用正则表达式和字符串.replace方法执行此操作:

var arr = ["a","b","c"];
var str = "Hello {1} is a friend of {2} and {3}"

var newstr = str.replace(/\{(\d)\}/gm, (_m, i) => {
  const index = Number(i) - 1;
  return arr[index]
});

console.log(newstr)