簡體   English   中英

使用匹配中的對象屬性查找進行Javascript正則表達式替換為“未定義”

[英]Javascript regex replace using object property lookup from match is “undefined”

嘗試執行正則表達式替換時出現以下問題:

這是我的字符串和正則表達式:

var content = "This is the city of {{city}}, located in the county of {{county}} and the state of {{state}}"
content.replace(/\{\{([a-zA-Z0-9]*)\}\}/g, '$1')

“這是城市的城市,位於縣和州的縣”

這是我的正則表達式替換的上下文對象:

var context = {city: "Abanda", county: "Chambers County", state: "Alabama"}
content.replace(/\{\{([a-zA-Z0-9]*)\}\}/g, context['$1'])

“這是未定義的城市,位於未定義的縣和未定義的州”

為什么我的正則表達式替換失敗並帶有undefined 我正在關注MDN的正則表達式替換和匹配文檔, 網址為: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#special-capturing-parentheses

在調試此問題時,我得到了以下內容,它着重說明了在regex替換方法內部訪問對象的屬性時可能存在問題:

content.replace(/\{\{([a-zA-Z0-9]*)\}\}/g, '$1')

“這是城市的城市,位於縣和州的縣”

content.replace(/\{\{([a-zA-Z0-9]*)\}\}/g, context)

這是[對象對象]的城市,位於[對象對象]的縣和[對象對象]的州

誰能解釋?

context['$1'] 未定義的; 您的context對象上沒有名為$1的屬性。

, ) 您可以提供一個回調函數作為String.prototype. replace( , )的第二個參數,而不是靜態的替換值String.prototype. replace( , ) , ) . String.prototype. replace( , ) 每次匹配都會調用回調函數...接收匹配的文本和任何捕獲組值作為參數。 您可以根據這些值進行處理,並根據上下文返回替換值。

 var content = "This is the city of {{city}}, located in the county of {{county}} and the state of {{state}}"; var context = { city: "Abanda", county: "Chambers County", state: "Alabama" }; var output = content.replace(/\\{\\{([a-z0-9]+)\\}\\}/gi, (match, key) => context[key]); console.log(output); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM