I want to replace ":player:" from my string with a player-name from localStorage. And if there are multiple ":player:" in the string do I want to replace ":player:" with a different name for each time it comes up in the string so for example.
Lets say that I have a string that looks something like this:
str = ":player: drink 5 sips if :player: has 5 fingers"
Then I want the output to be able to be.
str = "Alex drink 5 sips if Harry has 5 fingers"
My localStorage data looks like this:
namesArray = [["Alex",0],["Harry",1]]
I have tried different variants of str.replace() but it's not working the way that I want it to...
Does it exist something like this?
forEach(str.includes(":player:") => {
str.replace(":player:", localStorageName[randomNumber].name);
});
Use the replaceAll() method with a function as the replacement. It can then retrieve from localStorage and increment the index each time it's called.
localStorage.setItem('name', JSON.stringify(['Alex', 'Harry']));
let str = ":player: drink 5 sips if :player: has 5 fingers";
let index = 0;
str = str.replaceAll(':player:', () => JSON.parse(localStorage.getItem('name'))[index++]);
console.log(str);