Auto increment +1 in pattern javascript

I am trying to make a pattern where the code will auto-increment +1 to the last number in the pattern.
I wrote the code where it auto increments in a current pattern that is “ABC123” in the right manner but doesn’t know how to make it with my new pattern which is “ABC/11-22/1234”

var myPattern = 'ABC123';
let strings = myPattern.replace(/[0-9]/g, "");
let digits = (parseInt(myPattern.replace(/[^0-9]/g, "")) + 1).toString();
if (digits.length < 3) {
    digits = ("000" + digits).substr(-3);
}
myPattern = strings + digits;
console.log(myPattern) //ABC124

I want ABC/11-22/1234 becomes ABC/11-22/1235

/\d+$/

(now your challenge is; why is that the pattern?)

1 Like

this is right ? this is not working

Well, no, it’s not right. But it’s less to do with the pattern and moreso with the logic.

Try this instead:
Find (match) the string you want to replace (the numbers). Store that string. We’ll call that r.
parseInt r, add 1, convert back to a string, padStart it to be length 3. Store that string. We’ll call that s.
Replace r with s in the original input string. (You may want to regex-replace, in case r is repeated in the string; in which case replace the pattern with s.)

Hi @wawane7256, you might also consider specifying a function as the replacement; this way so you can apply the replacement logic directly, and don’t need to splice it with the original string afterwards:

const result = 'ABC/11-22/1234'.replace(/\d+$/, function (match) {
  // Do stuff here, like applying padding etc.
  return parseInt(match, 10) + 1
})

console.log(result) // 'ABC/11-22/1235'
2 Likes

but here suppose ‘ABC/11-22/03’ and I am adding +1 it shows ‘ABC/11-22/4’ but it should be ‘ABC/11-22/0004’

Something like this?

// generic zeroPad function
// zeroPad(12, 5) returns '00012'
const zeroPad = (num, pad = 1) => {
  return String(num).padStart(pad, '0')
}

const increment = (code) => {
  const parts = code.split('/')
  // pop the last part off of parts and convert to a number
  const last = parseInt(parts.pop(), 10) // 3

  // return the parts joined with '/'
  // e.g. zeroPad(3 + 1, 4) -> '0004'
  return [...parts, zeroPad(last + 1, 4)].join('/')
}

console.log(increment('ABC/11-22/03'))
// ABC/11-22/0004
1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.