我在这里做错了什么?
我的HTML
<form name="frm">
<textarea rows="10" id="uinput">some text here</textarea>
find 1: <input type="text" id="findbox1" value="e">
replace 1: <input type="text" id="replacebox1" value="666">
find 2: <input type="text" id="findbox2" value="o">
replace 2: <input type="text" id="replacebox2" value="000">
find 3: <input type="text" id="findbox3" value="t">
replace 3: <input type="text" id="replacebox3" value="777">
<button type="button" id="fnrbtn">find and replace</button>
</form>
我的JQuery
RegExp.escape = function(str) {
return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
};
$("#fnrbtn").click(function() {
var InputBox = $("#uInput").val(),
FindWhat = $('#findbox' + i).val(),
ReplaceWhat = $('#replacebox' + i).val(),
NewInputBox = '',
msg = '';
for (i = 1; i < counter; i++) {
msg += "\n Textbox #" + i + ": " + $('#findbox' + i).val() + " Replace #" + i + ": " + $('#replacebox' + i).val();
NewInputBox = InputBox.replace(new RegExp(RegExp.escape(FindWhat), "gi"), ReplaceWhat);
}
alert(msg);
$("#uInput").val(NewInputBox);
$('#uInput').select();
});
答案 0 :(得分:1)
您的FindWhat
和ReplaceWhat
位于for
循环之外,而我认为它们必须位于内部。
此外,未定义counter
。您需要在使用前对其进行初始化。
您的HTML包含$("#uinput")
,而不是{J}代码中的$("#uInput")
。
此外,您使用旧值InputBox
运行替换,而不是在上一次搜索和替换操作期间修改的值。
这是一个固定的代码:
RegExp.escape = function(str) {return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');};
$("#fnrbtn").click(function () {
var InputBox = $("#uinput").val(); // uInput > uinput
msg = '';
counter = 4;
for(i=1; i<counter; i++){
FindWhat = $('#findbox' + i).val();
ReplaceWhat = $('#replacebox' + i).val();
msg += "\n Textbox #" + i + ": " + $('#findbox' + i).val() + " Replace #" + i + ": " + $('#replacebox' + i).val();
InputBox = InputBox.replace(new RegExp(RegExp.escape(FindWhat), "gi"), ReplaceWhat);
}
alert(msg);
$("#uinput").val(InputBox);
$('#uinput').select();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="frm">
<textarea rows="10" id="uinput">some text here</textarea>
find 1: <input type="text" id="findbox1" value="e">
replace 1: <input type="text" id="replacebox1" value="666">
find 2: <input type="text" id="findbox2" value="o">
replace 2: <input type="text" id="replacebox2" value="000">
find 3: <input type="text" id="findbox3" value="t">
replace 3: <input type="text" id="replacebox3" value="777">
<button type="button" id="fnrbtn">find and replace</button>
</form>