使用JavaScript或jQuery获取并替换字符串上的最后一个数字 [英] Get and replace the last number on a string with JavaScript or jQuery

查看:65
本文介绍了使用JavaScript或jQuery获取并替换字符串上的最后一个数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有字符串:

var myStr =foo_0_bar_0;

我想我们应该有一个名为的函数getAndIncrementLastNumber(str)

and I guess we should have a function called getAndIncrementLastNumber(str)

所以,如果我这样做:

myStr = getAndIncrementLastNumber(str); //foo_0_bar_1

考虑到可能有另一个文本而不是 foo bar 并且可能没有下划线或者可能有多个下划线;

Taking on considerations that there could be another text instead of foo and bar and there might not be underscores or there might be more than one underscore;

有没有办法使用 JavaScript jQuery .replace()和一些 RegEx

Is there any way with JavaScript or jQuery with .replace() and some RegEx?

推荐答案

你可以使用正则表达式 / [0-9] +(?!。* [0-9])/ 查找字符串中的最后一个数字(来源: http://frightanic.wordpress.com/2007/06/08/regex-match-last-occurrence/ )。这个函数,使用带有match(),parseInt()和replace()的正则表达式,可以满足你的需要:

You can use the regular expression /[0-9]+(?!.*[0-9])/ to find the last number in a string (source: http://frightanic.wordpress.com/2007/06/08/regex-match-last-occurrence/). This function, using that regex with match(), parseInt() and replace(), should do what you need:

function increment_last(v) {
    return v.replace(/[0-9]+(?!.*[0-9])/, parseInt(v.match(/[0-9]+(?!.*[0-9])/), 10)+1);
}

可能不是非常有效,但对于短串,它应该没关系。

Probably not terribly efficient, but for short strings, it shouldn't matter.

编辑:这是一个稍微好一点的方法,使用回调函数而不是搜索字符串两次:

Here's a slightly better way, using a callback function instead of searching the string twice:

function increment_last(v) {
    return v.replace(/[0-9]+(?!.*[0-9])/, function(match) {
        return parseInt(match, 10)+1;
    });
}

这篇关于使用JavaScript或jQuery获取并替换字符串上的最后一个数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆