如何替换 JavaScript 中字符串中最后一次出现的两个字符之间的字符?

How do I replace a character between the last occurrence of two characters in a string in JavaScript?

我有一个名为 d[hotel][suite][0] 的输入文本字段。我如何将最后一个 [0] 替换为 [1][2] 等等?这可能使用 jQuery 还是我必须使用正则表达式的替换函数?

到目前为止我尝试过的:

the_name = $(this).attr('name');
the_name = the_name.replace(/[.*]/, '2');

没用

the_name = $(this).attr('name');
var start_pos = the_name.lastindexOf('[') + 1;
var end_pos = the_name.lastindexOf(']',start_pos);
var text_to_replace = the_name.substring(start_pos,end_pos);

不适用于 2 位以上的数字。

如有任何帮助,我们将不胜感激。

使用正则表达式可能更容易。

new_name = the_name.replace(/\[(\d+)\]$/, function(match, n) {
    return '[' + (parseInt(n, 10)+1) + ']');
});

正则表达式中的 $ 锚点使其匹配末尾的括号。当您使用函数作为替换时,它会使用匹配的字符串和每个捕获组作为参数调用该函数,并且 returns 用作替换。