JavaScript不替换所有元素

fro*_*sty 0 javascript jquery

我正在尝试替换表单元素的索引.我有以下内容

    var test = "<input name='[1].Id' value='598' type='hidden' /><input name='[1].OrderItemId' value='867' type='hidden' />";
    alert(test.replace('[1]', '[2]'));
Run Code Online (Sandbox Code Playgroud)

我得到了好奇的结果.第一个隐藏字段被第二个被忽略的替换

即我的回答是这样的:

"<input name='[1].Id' value='598' type='hidden' /><input name='[2].OrderItemId' value='867' type='hidden' />"
Run Code Online (Sandbox Code Playgroud)

编辑:

好的,谢谢这些方法适用于我的简单示例.但实际上我的字符串有点复杂.这是"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>
Run Code Online (Sandbox Code Playgroud)

这是js函数

    $('#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();
    });
Run Code Online (Sandbox Code Playgroud)

Mat*_*all 5

在JavaScript中,将字符串作为第一个参数传递,replace()只会替换第一个匹配项.你需要使用带有全局标志的正则表达式:

test.replace(/\[1\]/g, '[2]');
Run Code Online (Sandbox Code Playgroud)

额外的反斜杠(\)转义括号([和]).


编辑:响应OP的编辑,如果你想动态构建正则表达式,你不能使用正则表达式文字 - 这是由正斜杠(/)分隔的东西,而不是"编辑中的引号().你正在传入一个字符串replace(),我正在传递一个正则表达式字面值.使用JavaScript RegExp()构造函数来修复你的:

// The first argument is the regex, the second is a string of flags.
var previousIndex = new RegExp("\\[" + previousLength + "\\]", "g");

// Then, it's exactly the same as before.
// The second argument to replace is still a string.
var newRow = lastRow.html().replace(previousIndex, currentIndex);
Run Code Online (Sandbox Code Playgroud)

注意字符转义的差异.