powiększanie liczby w stringu

0

Mam pytanie. Mając string z zakonczoną cyfrą chce zwiekszyć tą cyfrę o 1
np: na wejsciu daje txt1 a na wyjsciu chce dostac txt2 lub txt22->txt23. Napisałem coś takiego, ale chyba w złym kierunku idę bo wydaje się te zadanie prostsze. Np moje rozwiaznie nie dziala dla takiego przypadku: txt0042 -> txt0043 ( bo dostaje txt43). Jesli mam samego stringa bez cyfr np:txt to na wyjsciu chce txt1. Napisałem cos takiego, ale nie jestem zbyt zadowolony z rązwiązania. Znacie moze lepszy sposob?

let i=1;

const fun = (txt) => {
  
    let numb = parseInt(`${txt}`.replace(/[^0-9]+/, ''));
    let text = (`${txt}`.replace(/[^a-zA-Z]+/g, ''));  
if (!parseInt(`${txt}`.replace(/[^0-9]+/, ''))){
    console.log(`${text}1`)
} else{
    numb++
    console.log(`${text}${numb}`)
}
}

fun('txt1')
0

Może coś takiego?

const fun = (txt) => {

    let numb = parseInt(`${txt}`.replace(/[^0-9]+/, ''));
    let digits = `${txt}`.replace(/[^0-9]+/, '');
    let text = (`${txt}`.replace(/[^a-zA-Z]+/g, ''));          
    numb++;

    let newDigits=numb.toString();
    if( (text.length+newDigits.length) > txt.length)
        console.log(  txt.slice( 0, txt.length-newDigits.length+1 ) + newDigits );
    else
        console.log(  txt.slice( 0, txt.length-newDigits.length ) + newDigits );
}

fun('txt99');
0

Moja propozycja rozwiązania...

Number.prototype.pad = function(size) {
    var s = String(this);
    while (s.length < (size || 2)) {s = "0" + s;}
    return s;
}

const fun = (txt) => {
    console.log(txt);
	
	let matches = txt.match(/\d+$/);
	if (matches) {
        let numb_str = matches[0];
		let numb_size = numb_str.length;
		let numb = parseInt(matches[0], 10);
		numb++
	    let result = txt.slice(0, txt.length-numb_size) + numb.pad(numb_size);
		console.log(result);
		
    }
    
}


fun('223tdx02tdf003')
1
function fn(x) {return x*1+1;}

str = "txt0042";
str = str.replace(/[1-9]\d*/g, fn);

alert(str);
0

Nie umiem w DżawaSkrypt.

def solve(s):
  n=i=len(s)
  while i>0 and s[i-1].isdigit():
    i-=1
  if i==n:
    return s
  pref,suf=s[:i],s[i:]
  k=1+int(suf)
  newsuf=str(k).zfill(n-i)
  return pref+newsuf

assert solve('')==''
assert solve('abc')=='abc'
assert solve('0')=='1'
assert solve('98')=='99'
assert solve('99')=='100'
assert solve('02')=='03'
assert solve('009')=='010'
assert solve('a1b')=='a1b'
assert solve('a2b0')=='a2b1'
assert solve('a3b1')=='a3b2'
assert solve('a4b9')=='a4b10'
assert solve('a5b999')=='a5b1000'
assert solve('a6b000')=='a6b001'
assert solve('a7b042')=='a7b043'
assert solve('a8b099')=='a8b100'

1 użytkowników online, w tym zalogowanych: 0, gości: 1