Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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');
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading