用正则表达式增加一个字符串中的数字 [英] Increment a number in a string in with regex
问题描述
我得到一个input元素的名称,它是一个带有数字的字符串( url1
)。我想以最简单快捷的方式将数字加1( url2
)。
我的方法是获得 \d
/ restofstring, ++
匹配,然后放在一起编号与restofstring。有没有更好的方法?
更新:
我的最终(虚拟)代码变成了:
var liNew = document.createElement('li');
liNew.innerHTML = liOld.innerHTML;
var els = Y.Dom.getChildrenBy(liNew,function(el){
return el.name.match(/ \d + $ /);
} // YUI method where函数是一个测试
for(var i = 0,el; el = els [i]; i ++){
el.name = el.name.replace(/ \ d + $ /,function( n){return ++ n});
}
list.appendChild(liNew);
'url1'.replace(/ \\ \\ d + $ /,function(n){return ++ n}); //url2
'url54'.replace(/ \ d + $ /,function(n){return ++ n}) ; //url55
在那里我们在字符串的末尾搜索一个数字,到 Number
,将它加1并放回到字符串中。我认为这与你的问题甚至是相同的算法。
参考:
-
String.prototype.replace
- 可以重试gex
I get the name of an input element, which is a string with a number (url1
). I want to increment the number by 1 (url2
) in the easiest and quickest way possible.
My way would be to get \d
/ restofstring, ++
the match, then put together number with restofstring. Is there a better way?
Update:
My final (dummy)code became:
var liNew = document.createElement('li');
liNew.innerHTML = liOld.innerHTML;
var els = Y.Dom.getChildrenBy(liNew, function(el) {
return el.name.match(/\d+$/);
} // YUI method where the function is a test
for (var i = 0, el; el = els[i]; i++) {
el.name = el.name.replace(/\d+$/, function(n) { return ++n });
}
list.appendChild(liNew);
How about:
'url1'.replace(/\d+$/, function(n){ return ++n }); // "url2"
'url54'.replace(/\d+$/, function(n){ return ++n }); // "url55"
There we search for a number at the end of the string, cast it to Number
, increment it by 1, and place it back in the string. I think that's the same algo you worded in your question even.
Reference:
String.prototype.replace
- can take a regex
这篇关于用正则表达式增加一个字符串中的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!