3 回答

TA貢獻1817條經驗 獲得超6個贊
您的代碼不起作用的原因是因為window['__' + "$1"]首先評估,所以:
sentence.replace(/__(\w+)/gs,window['__' + "$1"]);
...變成:
sentence.replace(/__(\w+)/gs, window['__$1']);
由于window['__$1']window 對象上不存在,這會導致undefined,因此您會得到:
sentence.replace(/__(\w+)/gs, undefined);
這就是導致您獲得undefined結果的原因。相反,您可以使用替換函數.replace()從第二個參數中獲取組,然后將其用于回調返回的替換值:
var __total = 8;
var sentence = "There are __total planets in the solar system";
const res = sentence.replace(/__(\w+)/gs, (_, g) => window['__' + g]);
console.log(res);
但是,像這樣訪問窗口上的全局變量并不是最好的主意,因為這不適用于局部變量或使用letor聲明的變量const。我建議您創建自己的對象,然后您可以像這樣訪問它:
const obj = {
__total: 8,
};
const sentence = "There are __total planets in the solar system";
const res = sentence.replace(/__(\w+)/gs, (_, g) => obj['__' + g]);
console.log(res);

TA貢獻1995條經驗 獲得超2個贊
你可以eval()在這里使用一個例子:
let __total = 8;
let str = "There are __total planets in the solar system ";
let regex = /__(\w+)/g;
let variables = str.match(regex);
console.log(`There are ${eval(variables[0])} planets in the solar system`)
let __total = 8;
let str = "There are __total planets in the solar system ";
let regex = /__(\w+)/g;
let variables = str.match(regex);
console.log(`There are ${eval(variables[0])} planets in the solar system`)

TA貢獻1846條經驗 獲得超7個贊
您必須拆分句子并使用變量來獲取分配給它的值。
所以你必須使用'+'號來分割和添加到句子中
因此,您只需使用正則表達式即可找到該詞。假設您將其存儲在名為myVar的變量中。然后你可以使用下面的代碼: sentence.replace(myVar,'+ myVar +');
所以你的最終目標是讓你的句子像:
sentence = "There are "+__total+" planets in the solar system";
添加回答
舉報