0

I'm trying to replace values from an array which are present in a string with another array. What is the best way to do this in Javascript? here is my code :

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']

and output should be like this

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

every value in both arrays is completely different from each other.

5
  • May you make your example a minimal reproducible example? Commented Oct 13, 2020 at 8:17
  • what are the values of those variables, Item1 ... Item4 and Product1 ... Product4 Commented Oct 13, 2020 at 8:17
  • @JaromandaX links Commented Oct 13, 2020 at 8:59
  • links, right so like http://example.com Commented Oct 13, 2020 at 9:30
  • @JaromandaX yes Commented Oct 13, 2020 at 18:39

3 Answers 3

1

You can replace the string using 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);

Sign up to request clarification or add additional context in comments.

2 Comments

I'm getting an error that replaceAll is not a function
On which browser are you chking?
1

I hope I have been helpful.

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

Comments

0

You can use template literal for e.g.

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

1 Comment

actually, I'm taking that string as input from the user so can't use template literal

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.