Regular expression to insert dash into numbers after 3 and 4 digits

I’m trying to insert dash into numbers but it is so hard to me… What I want to do is that insert dash into after 3 and 4 digits, for example,

replacing 123123412345 to 123-1234-12345.

The additional condition is that I replace it in input element. So I replace the number for every input event, i.e., I need to replace like

1 to 1
12 to 12
123 to 123
1231 to 123-1

1231234 to 123-1234
12312341 to 123-1234-1

123123412345 to 123-1234-12345

How can I do this using regex ??

Answer

You may try this regex:

  • Regex
(?<=^d{3}|^d{7})(?=d)
  • Substitution
-

Check the proof

const list = [
  1,
  12,
  123,
  1231,
  1231234,
  12312341,
  123123412345
];

const regex = /(?<=^d{3}|^d{7})(?=d)/g;
const result = list.map(e => regex[Symbol.replace](e, '-'));

console.log(result);