为了账号安全,请及时绑定邮箱和手机立即绑定

如何用数组的另一个值替换javascript中数组的值?

如何用数组的另一个值替换javascript中数组的值?

叮当猫咪 2023-05-11 10:12:17
我正在尝试用另一个数组替换字符串中存在的数组中的值。在 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."两个数组中的每个值都完全不同。
查看完整描述

3 回答

?
森林海

TA贡献2011条经验 获得超2个赞

您可以使用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);



查看完整回答
反对 回复 2023-05-11
?
开满天机

TA贡献1786条经验 获得超12个赞

我希望我有所帮助。


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);


查看完整回答
反对 回复 2023-05-11
?
互换的青春

TA贡献1797条经验 获得超6个赞

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


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]}.`


查看完整回答
反对 回复 2023-05-11
  • 3 回答
  • 0 关注
  • 94 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信