Javascript Regex找到一个字符串的实例并替换它后面的字符串

Javascript Regex find instance of one string and replace the string that comes after it

本文关键字:字符串 实例 替换 一个 Regex Javascript      更新时间:2023-09-26

我正在做一个项目,该项目将允许用户轻松更改API函数调用中的值。

api的值如下所示:FIRST_NAME=John&LAST_NAME=Doe&CUSTOMER_ID=284139&WHATEVER=XXXX

可以有任意数量的具有值的字段。每个字段都有不同的名称。

说我想把姓氏改成约翰逊。我也可以把身份证改成别的。用户可以选择要更改的值的字段。这让我觉得我需要一个新的RegExp对象。

我有字段名和变量中的新值,比如

var field = LAST_NAME (gotten from getElementById.value of a select option)
var value = Johnson (pulled from the value the user choose)

我正在寻找一个正则表达式,它将能够进入并找到字段名称,然后替换值。

我曾经使用过perl,并且正在思考类似于这个的东西

newApiCall = ApiCal.replace(new RegExp(/(.*)(&field=)(.*)&/), $3, value);

这将把所有的东西放在字段前的$1,&field=转换为$2,然后$3将是我要替换的值。希望3美元能被新的价值所取代。

有什么想法如何在javascript中做到这一点吗?

谢谢!

使用使用变量生成的动态正则表达式

var input = 'FIRST_NAME=John&LAST_NAME=Doe&CUSTOMER_ID=284139';  // your API string
var field = 'LAST_NAME';  // could be any alphanumeric value
var newValue = 'Heisenberg';  // if you are a fan of Breaking Bad ;)
var regex = new RegExp(field+'=([^&]*)');  // combines 'field' with the regex
var output = input.replace(regex, field + '=' + newValue);  // does the actual replacement part
console.log(output);  // check your browser's console after running this

了解更多:RegExp-JavaScript | MDN

"FIRST_NAME=John&LAST_NAME=Doe&CUSTOMER_ID=284139".replace(/((^|&)LAST_NAME=)[^&]*/, "$1" + encodeURIComponent("Johnson"))
//"FIRST_NAME=John&LAST_NAME=Johnson&CUSTOMER_ID=284139"

似乎你需要这样的东西:

var data = "FIRST_NAME=John&LAST_NAME=Doe&CUSTOMER_ID=284139";
var key = "FIRST_NAME";
data.replace(RegExp("((^|&)" + encodeURIComponent(key).replace(/'.'+'*'''/'[']'(')'?/g, "''$1") + "=)[^&]*"), "$1" + encodeURIComponent("Johnson"))
// "FIRST_NAME=Johnson&LAST_NAME=Doe&CUSTOMER_ID=284139"

我在节点(javascript)中执行了以下操作

var a = "FIRST_NAME=John&LAST_NAME=Doe&CUSTOMER_ID=284139";
var field = "LAST_NAME";
var value = "Johnson";
var re = new RegExp("(" + field + "=)([A-Za-z]*)([&'s]*)");
a.replace(re, '$1'+ value + '$3');
    'FIRST_NAME=John&LAST_NAME=Johnson&CUSTOMER_ID=284139'