0

After using the replace to put a slash after the second character, I became unable to delete it.

The code I'm using to make the replacement

Example of the problem

7
  • 1
    that is what happens when you change the text as the user types. Get to 2 and it adds the slash. Is there a reason you are not using date input? Commented Feb 19, 2020 at 15:13
  • That is exactly what you do with your replace: you put the / back there. Commented Feb 19, 2020 at 15:17
  • Yeah, but I want to know how to change the Regex, so it will behave as I want Commented Feb 19, 2020 at 15:19
  • The issue is the reg exp is doing what you want as you type the date.... not sure how you can change it to do it both ways. try moving the cursor and typing, you will run into other issues. You can listen for what key code is pressed and do thing differently Commented Feb 19, 2020 at 15:23
  • It's not a regex issue. You are over-aggressively acting upon user input. Commented Feb 19, 2020 at 15:36

1 Answer 1

2

Use event.key to check for the pressed key, and if the key is either Backspace or Delete return from the event handler without executing the insertion of the /:

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

input.addEventListener('keydown', () => {
    if(event.key === 'Backspace' || event.key === 'Delete') {
       return;
    }		
    if(input.value.length === 2)    input.value += '/'; 
});
<input>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.