如果我有字符串:
var myStr = "foo_0_bar_0";
我想我们应该有一个名为getAndIncrementLastNumber(str)
所以如果我这样做:
myStr = getAndIncrementLastNumber(str); // "foo_0_bar_1"
考虑到可能有另一个案文代替foo
and bar
可能没有underscores
或者可能有多个underscore
;
有什么办法与JavaScript
or jQuery
with .replace()
还有一些RegEx
?
您可以使用正则表达式/[0-9]+(?!.*[0-9])/
查找字符串中的最后一个数字(来源:http://frightanic.wordpress.com/2007/06/08/regex-match-last-occurrence/ 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);
}
可能效率不是很高,但对于短字符串来说,这应该不重要。
编辑:这是一个稍微更好的方法,使用回调函数而不是搜索字符串两次:
function increment_last(v) {
return v.replace(/[0-9]+(?!.*[0-9])/, function(match) {
return parseInt(match, 10)+1;
});
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)