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

181
Views
Replace part of string with new value for each time it appears in string, JavaScript

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);
});
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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);
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!