[英]How to increase each number in a string?
我需要在字符串中搜索其中的任何数字并将数字增加1.这样'sermon[thesis][1][name][2]'
成为'sermon[thesis][2][name][3]'
。
This will do the trick: 这样就可以了:
"sermon[thesis][1][name][2]".replace(/\[(\d+)\]/g, function(match, number) {
return "[" + (Number(number) + 1) + "]";
});
Working demo: jsFiddle . 工作演示: jsFiddle 。
EDIT: 编辑:
To increment the last number, you would add a dollar sign $
before the last /
, here's a demo: jsFiddle . 要增加最后一个数字,你可以在最后一个
/
之前添加一个美元符号$
,这是一个demo: jsFiddle 。
You can use replace
, it can actually take a function as the replacement "string". 你可以使用
replace
,它实际上可以将一个函数作为替换“字符串”。
var str = 'sermon[thesis][1][name][2]';
str = str.replace(/(\d+)/g, function(a){
return parseInt(a,10) + 1;
});
console.log(str); //'sermon[thesis][2][name][3]'
You can use the replace()
function to match any number with a regular expression and then return that value incremented by 1 to replace it: 您可以使用
replace()
函数将任何数字与正则表达式匹配,然后返回该值增加1以替换它:
var string = '[1][2]';
string.replace(/[0-9]+/g,function(e){return parseInt(e,10)+1})); //Returns [2][3]
You can do something like this: 你可以这样做:
var str = "sermon[thesis][1][name][2]";
var newStr = str.replace(new RegExp("\\d+", "g"), function (n) {
return parseInt(a, 10) + 1;
});
Basicly, the function would be called with the text been captured by the expression \\d+
,the text return from the function would be use to replace the captured text. 基本上,函数将被调用,文本被表达式
\\d+
捕获,函数返回的文本将用于替换捕获的文本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.