[英]How to replace last occurrence of characters in a string using 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) + ']');
});
正则表达式中的$
锚使其与末尾的括号匹配。 当您使用函数作为替换项时,它将使用匹配的字符串和每个捕获组作为参数调用该函数,并将返回的任何内容用作替换项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.