亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

用使用該字符串作為變量名的變量替換某些字符串

用使用該字符串作為變量名的變量替換某些字符串

慕娘9325324 2022-11-11 16:59:31
我有一些動態創建的變量。所有變量都使用雙下劃線('__')作為前綴。所以我想要做的是用變量替換句子中包含雙下劃線前綴的任何字符。這是一個例子:輸入var __total = 8; var sentence = "There are __total planets in the solar system";預期結果太陽系中有8顆行星這是我解析字符串的正則表達式,但它返回未定義:sentence.replace(/__(\w+)/gs,window['__' + "$1"]);
查看完整描述

3 回答

?
慕的地6264312

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


查看完整回答
反對 回復 2022-11-11
?
拉風的咖菲貓

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`)


查看完整回答
反對 回復 2022-11-11
?
喵喵時光機

TA貢獻1846條經驗 獲得超7個贊

您必須拆分句子并使用變量來獲取分配給它的值。

所以你必須使用'+'號來分割和添加到句子中

因此,您只需使用正則表達式即可找到該詞。假設您將其存儲在名為myVar的變量中。然后你可以使用下面的代碼: sentence.replace(myVar,'+ myVar +');

所以你的最終目標是讓你的句子像:

sentence = "There are "+__total+" planets in the solar system";


查看完整回答
反對 回復 2022-11-11
  • 3 回答
  • 0 關注
  • 139 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號