Dan*_*ris 0 javascript regex string textbox replace
我有一个名为的输入文本字段d[hotel][suite][0].我如何将取代过去[0]用[1]或[2]等等?这可能是使用jQuery还是我必须使用regex的替换功能?
到目前为止我尝试过的:
the_name = $(this).attr('name');
the_name = the_name.replace(/[.*]/, '2');
Run Code Online (Sandbox Code Playgroud)
没工作
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);
Run Code Online (Sandbox Code Playgroud)
不适用于2位数.
任何帮助,将不胜感激.
使用正则表达式可能更容易.
new_name = the_name.replace(/\[(\d+)\]$/, function(match, n) {
return '[' + (parseInt(n, 10)+1) + ']');
});
Run Code Online (Sandbox Code Playgroud)
正$则表达式中的锚点使其与末尾的括号匹配.当您使用函数作为替换函数时,它使用匹配的字符串调用函数,并将每个捕获组作为参数调用,并将其返回的任何内容用作替换函数.