Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

106
Views
Multiple replacements within the same variable

I have a string that looks like this:

mylist = `<div>some stuff</div>A lot of code in between<span>more stuff</span>`;

I want to replace some stuff with things and more stuff with many things so I do this:

 mylist = mylist.replace(`some stuff`, 'things');
 mylist = mylist.replace(`more stuff`, 'many things');

It works but I'm sure there must be a much better approach. What should it be?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You can chain the replace calls:

mylist = mylist.replace(`some stuff`, 'things').replace(`more stuff`, 'many things');

If you want to store the pairs in an object for scalability, you can loop through the object's entries (with Object.entries) and replace all occurences of each key with its value:

const obj = {
  "some stuff": "things",
  "more stuff": "many things"
}

var str = "<div>some stuff</div>A lot of code in between<span>more stuff</span>"

Object.entries(obj).forEach((k,v) => str = str.replace(k,v))

console.log(str)

about 4 years ago · Juan Pablo Isaza Report

0

You can first create a changes object which contain key-value of replace-replacement and then iterate over the key-value and replace the key with the value

This is better because if you have multiple replacements then It will work every time if you just add more replacer - replacement in the object itself.

You don't have to add extra replace statement, just add key-value in the changes and you are good to go.

let mylist = `<div>some stuff</div>A lot of code in between<span>more stuff</span>`;

const changes = {
  "some stuff": "things",
  "more stuff": "many things",
};

mylist = Object.entries(changes).reduce((str, [k, v]) => str.replace(k, v), mylist);
console.log(mylist)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!