简体   繁体   English

Javascript 正则表达式用实际变量值替换字符串变量

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

I would like "category/[categoryName]/[amount]" to become "category/movies/all" (replace "[variable-name]" with the value of the variable with the same name).我希望"category/[categoryName]/[amount]"变成"category/movies/all" (将“[variable-name]”替换为同名变量的值)。 I have this so far but I'm missing something:到目前为止我有这个,但我错过了一些东西:

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

but the value of searchUrl just becomes "category/undefined/undefined".searchUrl的值只是变成“类别/未定义/未定义”。

Is what I'm trying to do even possible?我想要做的甚至可能吗? Was that asked before and my question title is just malformed?以前有人问过吗,我的问题标题格式不正确? I know how to do this with 2 regexes, first getting the variable names then looping in them and substituting.我知道如何使用 2 个正则表达式来做到这一点,首先获取变量名,然后在它们中循环并替换。 However I would like to do it with one "replace" only.但是,我只想用一个“替换”来做到这一点。 Is that possible or I have to use 2 regexes?这是可能的还是我必须使用2个正则表达式?

If I understand correctly for this to work as dynamically as you state you will have to do the following如果我理解正确,它可以像您 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']);

Your dynamic variable will have to be stored globally for this work!为了这项工作,您的动态变量必须全局存储!

You're so close!你这么近! What you have now tries to replace [categoryName] with the global variable $1 , which doesn't exist.您现在尝试将[categoryName]替换为不存在的全局变量$1 What you want is to use searchUrl.replace(regex, categoryName) , assuming categoryName is dynamically set with the correct category.您想要的是使用searchUrl.replace(regex, categoryName) ,假设categoryName是使用正确的类别动态设置的。

It seems that with .replace you can enter multiple 'replacers', so you could say str.replace(regex, replacer1, replacer2, replacer3...) .似乎使用.replace您可以输入多个“替换器”,因此您可以说str.replace(regex, replacer1, replacer2, replacer3...) Alternatively, you can pass a function to replace a matched value each time one is found.或者,您可以传递 function 以在每次找到匹配值时替换匹配值。

I just modified your code to:我刚刚将您的代码修改为:

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"

Since your regex is global, it continues to find matches but since there is only 1 replacer in your original code, it replaces the match with that replacer.由于您的正则表达式是全局的,它会继续查找匹配项,但由于您的原始代码中只有 1 个替换器,它会用该替换器替换匹配项。

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

You may want to put your replacers into an array.您可能希望将替换器放入数组中。 Then with each match, use a function to replace the match with the value stored in the array, as shown in my example above.然后对于每个匹配项,使用 function 将匹配项替换为存储在数组中的值,如上面的示例所示。

Note: This example works for 2 matches only.注意:此示例仅适用于 2 个匹配项。

Hope this helps.希望这可以帮助。

MDN - Specifying a function as a parameter MDN - 指定 function 作为参数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM