CheeseFlavored
CheeseFlavored

Reputation: 2112

How can I do the same replace on multiple variables in Javascript

I want to do the same replace on multiple variables. Here's an example that works, but I have to write the replace statement for each variable. I could make the replace a function and call the function for each variable, but I was wondering if there's a more efficient way to do it in one line, something like string1,string2,string3(replace...

<script>
string1="I like dogs, dogs are fun";
string2="The red dog and the brown dog died";
string3="The dog likes to swim in the ocean";
string1=string1.replace(/dog/g,'cat');
string2=string2.replace(/dog/g,'cat');
string3=string3.replace(/dog/g,'cat');

alert(string1+"\n"+string2+"\n"+string3);
</script>

Upvotes: 0

Views: 158

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370659

Use an array instead, and .map to a new array, carrying out the replace operation on each:

const dogToCat = str => str.replace(/dog/g,'cat');
const strings = [
  "I like dogs, dogs are fun",
  "The red dog and the brown dog died",
  "The dog likes to swim in the ocean"
];
console.log(
  strings
    .map(dogToCat)
    .join('\n')
);

If you have to use standalone variables and reassign to them, then you can destructure the result, though it's ugly and probably isn't a great idea (consts are preferable, when possible):

const dogToCat = str => str.replace(/dog/g, 'cat');
let string1 = "I like dogs, dogs are fun";
let string2 = "The red dog and the brown dog died";
let string3 = "The dog likes to swim in the ocean";

([string1, string2, string3] = [string1, string2, string3].map(dogToCat));
console.log(string1 + "\n" + string2 + "\n" + string3);

Upvotes: 1

Related Questions