Home > Software engineering >  Regular expression to insert dash into numbers after 3 and 4 digits
Regular expression to insert dash into numbers after 3 and 4 digits

Time:10-20

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

CodePudding user response:

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);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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">
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related