How to auto generate `Ref number` on Invoice Form

I have Invoice Form in my POS System.
And I would like to auto generate Ref number + 1 base on the latest one.
1- Latest: INV001, -> INV002
2- Latest: IVN001-BB005, -> IVN001-BB006
3- Latest: BB005CC002DD -> BB005CC003DD

Easiest way is to just set it on the document before you insert

could example?
(how to replace last of string)

Now work fine with

String.prototype.replaceLast = function(what, replacement) {
    var pcs = this.split(what);
    var lastPc = pcs.pop();
    return pcs.join(what) + replacement + lastPc;
str.replaceLast(what, replacement)

If the number to change will be in a consistent/know/given location you could do :

someIdString[locationtoreplace] = parseInt(someIdString[locationtoreplace])++;