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

TA貢獻1786條經驗 獲得超13個贊
我希望我有所幫助。
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);

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]}.`
添加回答
舉報