Home > Blockchain >  Chain replace for the same character appearing multiple times
Chain replace for the same character appearing multiple times

Time:12-29

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

CodePudding user response:

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