Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

83
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');
7 months 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');
7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs