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

我正在尝试用另一个数组替换字符串中存在的数组中的值。在 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."

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


叮当猫咪
浏览 96回答 3
3回答

森林海

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

开满天机

我希望我有所帮助。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++) {&nbsp; &nbsp; var string = string.replace(array1[i], array2[i]);}console.log(string);

互换的青春

您可以使用模板文字,例如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&nbsp;${array1[3]}.`var replaced = `I've to but the ${array2[0]} along with ${array2[1]} and ${array2[2]}.&nbsp;From the ${array2[3]}.`
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript