使用 JavaScript 或 jQuery 获取并替换字符串上的最后一个数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11059054/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 11:57:35  来源:igfitidea点击:

Get and replace the last number on a string with JavaScript or jQuery

javascriptjqueryregexreplace

提问by Mr_Nizzle

If I have the string:

如果我有字符串:

var myStr = "foo_0_bar_0";

var myStr = "foo_0_bar_0";

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

我想我们应该有一个函数叫做 getAndIncrementLastNumber(str)

so if I do this:

所以如果我这样做:

myStr = getAndIncrementLastNumber(str); // "foo_0_bar_1"

myStr = getAndIncrementLastNumber(str); // "foo_0_bar_1"

Taking on considerations that there could be another text instead of fooand barand there might not be underscoresor there might be more than one underscore;

考虑到可能有另一个文本而不是foo和,bar并且可能没有underscores或可能不止一个underscore

Is there any way with JavaScriptor jQuerywith .replace()and some RegEx?

有没有办法 withJavaScriptjQuerywith.replace()和 some RegEx

回答by Brilliand

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:

您可以使用正则表达式/[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);
}

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

可能效率不高,但对于短字符串,这无关紧要。

EDIT: 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;
    });
}

回答by Fabrício Matté

Here's how I do it:

这是我的方法:

function getAndIncrementLastNumber(str) {
    return str.replace(/\d+$/, function(s) {
        return ++s;
    });
}

Fiddle

小提琴

Or also this, special thanks to Eric:

或者还有这个,特别感谢 Eric:

function getAndIncrementLastNumber(str) {
    return str.replace(/\d+$/, function(s) {
        return +s+1;
    });
}

Fiddle

小提琴

回答by Tats_innit

try this demo pleasehttp://jsfiddle.net/STrR6/1/orhttp://jsfiddle.net/Mnsy3/

请尝试此演示http://jsfiddle.net/STrR6/1/http://jsfiddle.net/Mnsy3/

code

代码

existingId = 'foo_0_bar_0';
newIdOnly = existingId.replace(/foo_0_bar_(\d+)/g, "");
alert(newIdOnly);

getAndIncrementLastNumber(existingId);

function getAndIncrementLastNumber(existingId){
    alert(existingId);
newId = existingId.replace(/(\d+)/g, function(match, number) {
    return parseInt(number) + 1;
});
alert(newId);
}
?

or

或者

   existingId = 'foo_0_bar_0';
newIdOnly = existingId.replace(/foo_0_bar_(\d+)/g, "");
alert(newIdOnly);

getAndIncrementLastNumber(existingId);

function getAndIncrementLastNumber(existingId){
    alert(existingId);
    newId = existingId.replace(/\d+$/g, function(number) {
    return parseInt(number) + 1;
});
alert("New ID ==> " + newId);
}
?

回答by Krishna

Will the numbers be seperated with some characters? What I understood from you question is your string may look like this 78_asd_0_798_fgssdflh__0_2323 !! If this is the case, first you need to strip out all the characters and underscores in just one go. And then whatever you have stripped out you can either replace with comma or some thing.

数字会被一些字符分隔吗?我从你的问题中了解到你的字符串可能看起来像这样 78_asd_0_798_fgssdflh__0_2323 !如果是这种情况,首先您需要一次性去除所有字符和下划线。然后无论您删除什么,您都可以用逗号或其他东西替换。

So you will basically have str1: 78_asd_0_798_fgssdflh__0_2323 ; str2: 78,0,0,798,2323.

所以你基本上会有 str1: 78_asd_0_798_fgssdflh__0_2323 ; str2:78,0,0,798,2323。

str2 need not be a string either you can just save them into a variable array and get the max number and increment it.

str2 不必是字符串,您也可以将它们保存到变量数组中并获取最大数量并递增它。

My next question is does that suffice your problem? If you have to replace the largest number with this incremented number then you have to replace the occurence of this number in str1 and replace it with your result.

我的下一个问题是这足以解决您的问题吗?如果你必须用这个递增的数字替换最大的数字,那么你必须替换这个数字在 str1 中的出现并用你的结果替换它。

Hope this helps. For replace using jquery, you can probably look into JQuery removing '-' character from stringit is just an example but you will have an idea.

希望这可以帮助。对于使用 jquery 替换,您可能可以查看JQuery 从字符串中删除 '-' 字符,这只是一个示例,但您会有一个想法。

回答by sarath

If you want to only get the last number of string, Here is a good way using parseInt()

如果您只想获取字符串的最后一个数字,这是使用 parseInt() 的好方法

if(Stringname.substr(-3)==parseInt(Stringname.substr(-3)))
var b=Stringname.substr(-3);
else if(Stringname.substr(-2)==parseInt(Stringname.substr(-2)))
var b=Stringname.substr(-2);
else
var b=Stringname.substr(-1);

It checks and give the correct answer and store it in variable b for 1 digit number and upto 3 digit number. You can make it to any if you got the logic

它检查并给出正确答案,并将其存储在变量 b 中,用于 1 位数字和最多 3 位数字。如果你有逻辑,你可以做到任何

回答by André Pena

@Brilliant is right, +1, I just wanted to provide a version of his answer with 2 modifications:

@Brilliant 是对的,+1,我只是想提供他的答案版本,并进行了 2 处修改:

  • Remove the unnecessary negative look-aheadoperator.
  • Add the ability to add a number in the end, in case it doesn't exist.
  • 删除不必要的negative look-ahead运算符。
  • 添加最后添加数字的功能,以防它不存在。

```

``

/**
 * Increments the last integer number in the string. Optionally adds a number to it
 * @param {string} str The string
 * @param {boolean} addIfNoNumber Whether or not it should add a number in case the provided string has no number at the end
 */
function incrementLast(str, addIfNoNumber) {
    if (str === null || str === undefined) throw Error('Argument \'str\' should be null or undefined');
    const regex = /[0-9]+$/;
    if (str.match(regex)) {
        return str.replace(regex, (match) => {
            return parseInt(match, 10) + 1;
        });
    }
    return addIfNoNumber ? str + 1 : str;
}

Tests:

测试

describe('incrementLast', () => {
        it('When 0', () => {
            assert.equal(incrementLast('something0'), 'something1');
        });
        it('When number with one digit', () => {
            assert.equal(incrementLast('something9'), 'something10');
        });
        it('When big number', () => {
            assert.equal(incrementLast('something9999'), 'something10000');
        });
        it('When number in the number', () => {
            assert.equal(incrementLast('1some2thing9999'), '1some2thing10000');
        });
        it('When no number', () => {
            assert.equal(incrementLast('1some2thing'), '1some2thing');
        });
        it('When no number padding addIfNoNumber', () => {
            assert.equal(incrementLast('1some2thing', true), '1some2thing1');
        });
    });

回答by mgraph

in regextry this:

正则表达式中试试这个:

function getAndIncrementLastNumber(str){
   var myRe = /\d+[0-9]{0}$/g;  
   var myArray = myRe.exec(str);
   return parseInt(myArray[0])+1;?
}

demo : http://jsfiddle.net/F9ssP/1/

演示:http: //jsfiddle.net/F9ssP/1/