Skip to content
Advertisement

How to use “for” along with string replace?

I want to make several replacements in the same string. I have this:

ignoredids = [{"ignoredid":"3329"},{"ignoredid":"25895"}];
userlist = `<div id="u343">something</div><div id="u3143">something</div><div id="u25895">something</div><div id="u5343">something</div><div id="u3329">something</div>`;

after the replacements it should look like this:

<div id="u343">something</div><div id="u3143">something</div><div id="u25895">ignore this</div><div id="u5343">something</div><div id="u3329">ignore this</div>

So I tried:

for (let { ignoredid } of ignoredids) {
  mylist = userlist.replace(`<div id="u${ignoredid}">something</div>`,`<div id="u${ignoredid}">ignore this</div>`);        
} 

but it doesnt seem to do anything. What is wrong?

Advertisement

Answer

The way you wrote it now, it will only replace on the last id and assign it to the mylist variable, because .replace does not mutate the string.

If we assign to userlist instead of mylist it will work the way you want it to work, because then we’re actually modifying the string on every iteration:

ignoredids = [{"ignoredid": "3329"}, {"ignoredid": "25895"}];
userlist = `<div id="u343">something</div><div id="u3143">something</div><div id="u25895">something</div><div id="u5343">something</div><div id="u3329">something</div>`;

for (let { ignoredid} of ignoredids) {
  userlist = userlist.replace(`<div id="u${ignoredid}">something</div>`, `<div id="u${ignoredid}">ignore this</div>`);
}

document.getElementById("myDiv").innerHTML = userlist;
<div id="myDiv"></div>
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement