-1

I'm trying to write phone input masking function. Here it is:

let input = document.querySelector('input');

input.addEventListener('input', ()=>{
    let x = event.target.value.replace(/\D/g, '').match(/(\d{0,1})(\d{0,3})(\d{0,3})(\d{0,2})(\d{0,2})/);
    event.target.value = !x[2] ? x[1] : '+' + x[1] + ' (' + x[2] + ') ' + x[3] + (x[4] ? '-' + x[4] : '') + (x[5] ? '-' + x[5] : '');
})
<input />

It works, but with one problem. When I press the backspace key, I erase the phone number to something like +1 (111). Such an entry is valid for the regular expression, and the string is replaced by itself

ggorlen
  • 44,755
  • 7
  • 76
  • 106
Oleg
  • 49
  • 1
  • 6
  • Welcome to SO! I'm not really clear on the desired behavior or what the question is, exactly. You want to be able to backspace through the entire string? If so, you can check which key was pressed and if it was backspace, permit the digit to be removed. – ggorlen Aug 16 '20 at 23:22
  • @ggorlen Yes, I would like exactly this behavior from my function. And one more question, if I may. My question's rating is "-1" now. I guess I made a mistake when I asked this question. Was it an insufficiently clear statement of the essence, or something else? – Oleg Aug 17 '20 at 09:32
  • I'm not the downvoter so I can't speak for them, but I do recommend visiting [ask] and see [when is it justifiable to DV a question](https://meta.stackoverflow.com/questions/252677/when-is-it-justifiable-to-downvote-a-question). -1 isn't too bad but I'd be happy to upvote if you don't mind editing to ask a concrete question. – ggorlen Aug 17 '20 at 15:35

1 Answers1

0

Per @ggorlen's suggestion in the comments, here is one way to do this:

let input = document.querySelector('input');

input.addEventListener('keydown', (event)=>{
    if (event.key === "Backspace" || event.key === "Delete") return;
    let x = event.target.value.replace(/\D/g, '').match(/(\d{0,1})(\d{0,3})(\d{0,3})(\d{0,2})(\d{0,2})/);
    event.target.value = !x[2] ? x[1] : '+' + x[1] + ' (' + x[2] + ') ' + x[3] + (x[4] ? '-' + x[4] : '') + (x[5] ? '-' + x[5] : '');
})
<input maxlength=18 />
jdaz
  • 5,964
  • 2
  • 22
  • 34
  • Yes, I thought about this too, but wanted to find a more elegant solution. I assumed that the expression I was using was not entirely correct. Anyway, it works. Thank you for your answer! – Oleg Aug 17 '20 at 09:32
  • Another solution would be to keep your original version but change the logic for the replacement: `+ ' (' + x[2] + ') ' + x[3]` becomes `+ ((x[2] && x[3]) ? ' (' + x[2] + ') ' + x[3] : x[2])` – jdaz Aug 17 '20 at 11:12