Reputation: 76
What am I doing wrong here?
My 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>
My 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();
});
Upvotes: 2
Views: 941
Reputation: 626747
Your FindWhat
and ReplaceWhat
are placed outside of the for
loop, while I think they must be inside.
Also, counter
is not defined. You need to initialize it before use.
And your HTML contains $("#uinput")
, not $("#uInput")
as in the JQuery code.
Besides, you run replacements using the old value InputBox
, not the modified value during the previous search and replace operation.
Here is a fixed code:
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>
Upvotes: 1