链式替换多次出现的同一个字符

Chain replace for the same character appearing multiple times

假设我有一个这样的字符串

Danny is ? James is ? Allen is ?

我想将其替换为

Danny is great James is wonderful Allen is magnificent

如何使用 replace 来实现?

我正在尝试做类似

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

但我刚得到:

Danny is great James is great Allen is great

如果情况是这样的:

Danny is ? James is # Allen is $

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

它会按预期工作,但由于它是同一个字符,所以它不起作用。

有没有比做下面的事情更简洁的方法来实现这个目标?

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

您正在使用带 /g(意思是:“全局”)选项的正则表达式替换函数,这意味着它将替换“?”字符串中无处不在。

只替换出现一次的“?”一次,只用一个普通的字符串来查找,例如:string.replace('?', 'great')

因此,您的完整示例是:

string = string.replace('?', 'great ') 
string = string.replace('?', 'wonderful ')
string = string.replace('?', 'magnificent');