簡體   English   中英

Javascript 正則表達式用實際變量值替換字符串變量

[英]Javascript regex replace in-string variable with actual variable value

我希望"category/[categoryName]/[amount]"變成"category/movies/all" (將“[variable-name]”替換為同名變量的值)。 到目前為止我有這個,但我錯過了一些東西:

let categoryName = "movies"; // example variable, set somewhere else
let amount = "all"; // example variable, set somewhere else
...
let searchUrl = "category/[categoryName]/[amount]"; // Set dynamically, could be any params
let regex = /\[(.+?)\]/ug;
searchUrl = searchUrl.replace(regex, window['$1']);

searchUrl的值只是變成“類別/未定義/未定義”。

我想要做的甚至可能嗎? 以前有人問過嗎,我的問題標題格式不正確? 我知道如何使用 2 個正則表達式來做到這一點,首先獲取變量名,然后在它們中循環並替換。 但是,我只想用一個“替換”來做到這一點。 這是可能的還是我必須使用2個正則表達式?

如果我理解正確,它可以像您 state 一樣動態地工作,您將必須執行以下操作

// example variable, you need to use var so its 
// available on the window otherwise this will not work
var categoryName = "movies"; 
...
let searchUrl = "category/[categoryName]/all";
let regex = /\[(.+?)\]/ug;
let variableName = searchUrl.match(regex)[0];
searchUrl = searchUrl.replace(regex, window['variableName']);

為了這項工作,您的動態變量必須全局存儲!

你這么近! 您現在嘗試將[categoryName]替換為不存在的全局變量$1 您想要的是使用searchUrl.replace(regex, categoryName) ,假設categoryName是使用正確的類別動態設置的。

似乎使用.replace您可以輸入多個“替換器”,因此您可以說str.replace(regex, replacer1, replacer2, replacer3...) 或者,您可以傳遞 function 以在每次找到匹配值時替換匹配值。

我剛剛將您的代碼修改為:

let categoryName = "movies"; // example variable, set somewhere else
let amount = "all"; // example variable, set somewhere else

// previous answer suggestion
// let replacers = [categoryName, amount];

let searchUrl = "category/[categoryName]/[amount]"; // Set dynamically, could be any params
let regex = /\[(.+?)\]/gu;
let replacers = searchUrl.match(regex).map( m => m.replace(/\[|\]/g,''));
searchUrl = searchUrl.replace(regex, () => { let val = eval(replacers.shift()); return val; });

output => "category/movies/all"

由於您的正則表達式是全局的,它會繼續查找匹配項,但由於您的原始代碼中只有 1 個替換器,它會用該替換器替換匹配項。

categories/undefined/undefined (使用searchUrl.replace(regex, window['$1']);

您可能希望將替換器放入數組中。 然后對於每個匹配項,使用 function 將匹配項替換為存儲在數組中的值,如上面的示例所示。

注意:此示例僅適用於 2 個匹配項。

希望這可以幫助。

MDN - 指定 function 作為參數

暫無
暫無

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

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