The code is adding all types at one instead of stopping at where I want

I have a piece of code, what I wish to do is for every a followed by some number add that said specific number to my total and if its b subtract the number. of course if neither a or b has no number following it, it should add/subtract 1 from total.

I think I know where my mistake is (its probably my regex) since its doing global search (maybe).

Following is my code :

const check= (a, b) => [...a.matchAll(RegExp(b+"(\d*)","g"))].reduce( 
                     (A[,C]) => eval( `A ${b=='a'?'+':b=='b'?'-':''} +C`),0)
// beautified a bit ^^ to increase readibility

Desen = code => {
    AC = 0; // accumulation
    String_ = ''
    ans = ""
        (b, _) => {
      if(b=='a') {
        if(/[1-9]/.test(code[_+1]) ) {
          AC += check(code, 'a')
        console.log("using check : " + check(code, 'a'))
        }else AC++
      if(b=='b') {
          AC -= check(code, 'b')
        else AC--
      if(b=='n') AC=0
            if(b == 'g') String_+= String.fromCharCode(AC)
          if(b == 'x') 
          ans+= code[_-1]=='g'?(String_+(String_='')):AC

    return ans

Explanation :
a adds (followed by number adds that otherwise adds), opposite for b, n resets AC. g converts AC into ASCII equivalent, x prints.

Right now its now working

Examples :

Desen ("aaa13x")                   ----> 15 (2 + 13 = 15 NOT 2 + 14) works

Desen ("a13xna2x")                 ----> 1530 (??) how (13print reset 2print) (132 it should give) wrong

Desen (a97gxa2)                   -----> 99 gives c wrong (should give a a2 should do nothing since x is not here)

Desen(b97xa2)                     -----> 97 (ans should be -97)

// Rest of examples for a can also be added on b as well. didn't write so it doesn't get too long 

My theory :

My g in regex is probably messing it up its getting all and then merely giving double second time (i obviously got no idea how to fix it). Regarding b I have no idea where its going wrong

Still haven’t figured out why n ain’t working.

Can anyone explain what went wrong (was my guess correct or wrong), and how I could go about fixing it


adding this as an answer as the code does not format well in comments. you may be able to process the entire string in one pass with the following (excluding the g option)

const check= (a) => [...a.matchAll(RegExp("[ab](\d*)|[gnx]","g"))].reduce(
  (A,C,I) => {
    console.log("index = " + I)
    if ("ab".includes(C[0][0])) A += Number(C[1]==""?1:C[1])*(C[0][0]=="a"?1:-1)
    if (C[0][0] == "n") return 0
    if (C[0][0] == "x") console.log(A)
    return A
  }, 0)
s = "aa10xabb5x" 
x = check(s)