I’m trying replace the index of form elements. I have the following
var test = "<input name='[1].Id' value='598' type='hidden' /><input name='[1].OrderItemId' value='867' type='hidden' />";
alert(test.replace('[1]', '[2]'));
I’m getting curious results. The first hidden field is replaced by the second is ignored
ie my response is something like this:
"<input name='[1].Id' value='598' type='hidden' /><input name='[2].OrderItemId' value='867' type='hidden' />"
EDIT:
OK, thanks these methods worked on my simple example. However in reality my string is a bit more complex. Here is the contents of “var lastRow “
<td>
<a class="deleteAddress" href="#">
<img alt="remove" src="/images/icons/delete_button.gif">
</a></td>
<td class="p-5" width="100">
<input name="[1].Id" value="612" type="hidden">
<input name="[1].OrderItemId" value="868" type="hidden">
<input class="itemAddressQuantity" name="[1].Quantity" value="" type="text">
</td>
<td class="p-5" width="100">
<select name="[1].AddressId"><option value="2">address1</option></select>
</td>
and here is the js function
$('#addNewAddress').click(function (event) {
event.preventDefault();
var length = $('.table-item-address tbody').find('tr').length;
var previousLength = length - 1;
var previousIndex = "/\[" + previousLength + "\]/g";
var currentIndex = "[" + length + "]";
var lastRow = $('.table-item-address tbody tr').last();
alert(lastRow.html()); // html is shown above
var newRow = lastRow.html().replace(previousIndex, currentIndex);
$('.table-item-address tr').last().after('<tr>' + newRow + '</tr>');
AdjustValues();
});
In JavaScript, passing a string as the first parameter to
replace()will only replace the first occurrence. You need to use a regex, with the global flag:The extra backslashes (
\) escape the brackets ([and]).Edit: responding to the OP’s edit, if you want to dynamically build a regex, you can’t use a regex literal – that’s the thing delimited by forward slashes (
/), not quotes (") as in your edit. You’re passing a string intoreplace(), I’m passing in a regex literal. Use the JavaScriptRegExp()constructor to fix yours:Note the difference in character escaping.