Home > Net >  Multiple replacements within the same same variable
Multiple replacements within the same same variable

Time:10-30

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?

CodePudding user response:

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)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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)
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related