-2

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 ??

wallah
  • 1,964
  • 5
  • 27
  • 48
  • 1
    I believe this can be achieved with format on the length of the input on change. You may refer to this page [Insert dash after every 4th character in input](https://stackoverflow.com/questions/11632525/insert-dash-after-every-4th-character-in-input) @wallah – dev_integral Oct 20 '21 at 01:07

2 Answers2

1

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);
Hao Wu
  • 17,573
  • 6
  • 28
  • 60
  • This doesn't feel efficient. You are checking two lookbehinds and one lookahead on every character while looking for qualifying positions to add the `-`. Right? – mickmackusa Oct 20 '21 at 02:45
0

Suppose it needs to split the first 3 next 4 digits only, it can be done with following regexp replacement

str.replace(/((?<!\d)\d{3}(?!\b)|(?<=^\d{3})\d{4}(?!\b))/g, '$1-')

Input string has to be all digits

document.getElementById('input').addEventListener('keyup', (e) => {
e.target.value = e.target.value.split('-').join('').replace(/((?<!\d)\d{3}(?!\b)|(?<=^\d{3})\d{4}(?!\b))/g, '$1-');
});

['1', '12', '123', '1231', '12312', '123123', '1231234', '12312341', '123123412', '1231234123', '12312341234', '123123412345']
.forEach(t => console.log(t.replace(/((?<!\d)\d{3}(?!\b)|(?<=^\d{3})\d{4}(?!\b))/g, '$1-')));
<input id="input" type="text" size="20">
ProDec
  • 5,390
  • 1
  • 3
  • 12