3 回答

TA貢獻(xiàn)1817條經(jīng)驗(yàn) 獲得超6個(gè)贊
您的代碼不起作用的原因是因?yàn)閣indow['__' + "$1"]首先評(píng)估,所以:
sentence.replace(/__(\w+)/gs,window['__' + "$1"]);
...變成:
sentence.replace(/__(\w+)/gs, window['__$1']);
由于window['__$1']window 對(duì)象上不存在,這會(huì)導(dǎo)致undefined,因此您會(huì)得到:
sentence.replace(/__(\w+)/gs, undefined);
這就是導(dǎo)致您獲得undefined結(jié)果的原因。相反,您可以使用替換函數(shù).replace()從第二個(gè)參數(shù)中獲取組,然后將其用于回調(diào)返回的替換值:
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);
但是,像這樣訪問(wèn)窗口上的全局變量并不是最好的主意,因?yàn)檫@不適用于局部變量或使用letor聲明的變量const。我建議您創(chuàng)建自己的對(duì)象,然后您可以像這樣訪問(wèn)它:
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貢獻(xiàn)1995條經(jīng)驗(yàn) 獲得超2個(gè)贊
你可以eval()在這里使用一個(gè)例子:
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貢獻(xiàn)1846條經(jīng)驗(yàn) 獲得超7個(gè)贊
您必須拆分句子并使用變量來(lái)獲取分配給它的值。
所以你必須使用'+'號(hào)來(lái)分割和添加到句子中
因此,您只需使用正則表達(dá)式即可找到該詞。假設(shè)您將其存儲(chǔ)在名為myVar的變量中。然后你可以使用下面的代碼: sentence.replace(myVar,'+ myVar +');
所以你的最終目標(biāo)是讓你的句子像:
sentence = "There are "+__total+" planets in the solar system";
添加回答
舉報(bào)