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

221
Views
Chain replace for the same character appearing multiple times

Let's say I have a string like so

Danny is ? James is ? Allen is ?

And I want to replace it to

Danny is great James is wonderful Allen is magnificent

How can I use replace to do it?

I'm attempting to do something like

string.replace(/\?/g, 'great ').replace(/\?/g, 'wonderful ').replace(/\?/g, 'magnificent');

but I just get:

Danny is great James is great Allen is great

If the case was something like:

Danny is ? James is # Allen is $

string.replace(/\?/g, 'great ').replace(/\#/g, 'wonderful ').replace(/\$/g, 'magnificent');

It would work as expected, but since it's the same character it's not working.

Is there a neater way to achieve this than doing something like below?

string = string.replace(/\?/g, 'great ') 
string = string.replace(/\?/g, 'wonderful ')
string = string.replace(/\?/g, 'magnificent');
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You are using the replace function with a regular expression with the /g (meaning: "global") option, which means it will replace the '?' everywhere in the string.

To replace only one occurence of '?' at a time, just use a normal string to find, eg: string.replace('?', 'great')

So, your full example would be:

string = string.replace('?', 'great ') 
string = string.replace('?', 'wonderful ')
string = string.replace('?', 'magnificent');
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!