Mr_*_*zle 9 javascript regex jquery replace
如果我有字符串:
var myStr = "foo_0_bar_0";
我想我们应该有一个叫做的函数 getAndIncrementLastNumber(str)
所以,如果我这样做:
myStr = getAndIncrementLastNumber(str); // "foo_0_bar_1"
以上的考虑,有可能是另一种文本,而不是foo和bar有可能不是underscores 或可能有不止一个underscore;
是否有任何方式与JavaScript或jQuery有.replace()一些RegEx?
Bri*_*and 17
您可以使用正则表达式/[0-9]+(?!.*[0-9])/查找字符串中的最后一个数字(来源:http://frightanic.wordpress.com/2007/06/08/regex-match-last-occurrence/).这个函数使用带有match(),parseInt()和replace()的正则表达式,可以满足你的需要:
function increment_last(v) {
return v.replace(/[0-9]+(?!.*[0-9])/, parseInt(v.match(/[0-9]+(?!.*[0-9])/), 10)+1);
}
Run Code Online (Sandbox Code Playgroud)
可能不是非常有效,但对于短串,它应该没关系.
编辑:这是一个稍微好一点的方法,使用回调函数而不是搜索字符串两次:
function increment_last(v) {
return v.replace(/[0-9]+(?!.*[0-9])/, function(match) {
return parseInt(match, 10)+1;
});
}
Run Code Online (Sandbox Code Playgroud)
我是这样做的:
function getAndIncrementLastNumber(str) {
return str.replace(/\d+$/, function(s) {
return ++s;
});
}
Run Code Online (Sandbox Code Playgroud)
或者这也是特别感谢Eric:
function getAndIncrementLastNumber(str) {
return str.replace(/\d+$/, function(s) {
return +s+1;
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10516 次 |
| 最近记录: |