【问题标题】:How to replace value of array in javascript with another value of array?如何用另一个数组值替换javascript中的数组值?
【发布时间】:2021-01-27 13:22:27
【问题描述】:

我正在尝试用另一个数组替换字符串中存在的数组中的值。在 Javascript 中执行此操作的最佳方法是什么? 这是我的代码:

var string = "I've to but the Item1 along with Item2 and Item3. From the Item4."
var array1 = ['Item1', 'Item2', 'Item3', 'Item4']
var array2 = ['Product1', 'Product2', 'Product3', 'Product4']

输出应该是这样的

var replaced = "I've to but the Product1 along with Product2 and Product3. From the Product4."

两个数组中的每个值都完全不同。

【问题讨论】:

  • 你可以把你的例子设为minimal reproducible example吗?
  • 这些变量的值是多少,Item1 ... Item4Product1 ... Product4
  • @JaromandaX 链接
  • 链接,就像http://example.com
  • @JaromandaX 是的

标签: javascript arrays str-replace array-replace


【解决方案1】:

您可以使用String.prototype.replaceAll替换字符串

const input = "I've to but the Item1 along with Item2 and Item3. From the Item4.";
const original = ['Item1', 'Item2', 'Item3', 'Item4'];
const target = ['Product1', 'Product2', 'Product3', 'Product4'];

let result = input;
original.forEach((item, index) => {
  result = result.replaceAll(item, target[index]);
});

console.log(result);

【讨论】:

  • 我收到一个错误,replaceAll 不是函数
  • 你在哪个浏览器上查看?
【解决方案2】:

您可以使用模板文字,例如

var array1 = [Item1, Item2, Item3, Item4];
var array2 = [Product1, Product2, Product3, Product4]
var string = `I've to but the ${array1[0]} along with ${array1[1]} and ${array1[2]}. From the 
${array1[3]}.`
var replaced = `I've to but the ${array2[0]} along with ${array2[1]} and ${array2[2]}. 
From the ${array2[3]}.`

【讨论】:

  • 实际上,我将该字符串作为用户的输入,因此不能使用模板文字
【解决方案3】:

希望我对你有所帮助。

var array1 = ['Item1', 'Item2', 'Item3', 'Item4'];
var array2 = ['Product1', 'Product2', 'Product3', 'Product4'];
var string = "I've to but the Item1 along with Item2 and Item3. From the Item4.";

for (var i = 0; i < array1.length; i++) {
    var string = string.replace(array1[i], array2[i]);
}

console.log(string);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-07-21
    • 2011-04-19
    • 1970-01-01
    • 1970-01-01
    • 2015-03-31
    • 1970-01-01
    • 2014-04-15
    相关资源
    最近更新 更多