我正在开发一个允许用户轻松更改API函数调用值的工作项目。
api的值如下所示:FIRST_NAME = John& LAST_NAME = Doe& CUSTOMER_ID = 284139& WHATEVER = XXXX
可以有任意数量的具有值的字段。每个字段都有不同的名称。
我想要将姓氏改为约翰逊。我还想将ID更改为某些内容。用户可以选择要更改其值的字段。这让我觉得我需要一个新的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中执行此操作?
谢谢!
答案 0 :(得分:1)
使用使用变量生成的动态正则表达式:
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

答案 1 :(得分:0)
"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"
答案 2 :(得分:0)
我在节点(javascript)中执行了以下操作
<section id="modal-report" class="badge-overlay-report modal report">
<header>
<h3>Report Post</h3>
<p>What do you report this post for?</p>
<a class="btn-close badge-overlay-close" href="#">✖</a>
</header>
<form id="form-modal-report" class="popup-report" action="" onsubmit="return true;">
<div class="field checkbox">
<label><input name="radio-report" type="radio" value="1"> Contains a trademark or copyright violation</label>
</div>
<div class="field checkbox">
<label><input name="radio-report" type="radio" value="2"> Spam, blatant advertising, or solicitation</label>
</div>
<div class="field checkbox">
<label><input name="radio-report" type="radio" value="3"> Contains offensive materials/nudity</label>
</div>
<div class="field checkbox">
<label><input name="radio-report" type="radio" value="4"> Repost of another post on 9GAG</label>
<input id="jsid-repost-link" type="text" class="text" placeholder="http://9gag.com/gag/post_ID">
</div>
<div class="btn-container">
<input type="submit" value="Submit" data-text-loading="Please wait ...">
</div>
</form>
</section>