skip to Main Content

I have a card-number input which when type numbers in it, it will be formatted as a group of "4 digits" and a "whitespace" after it instead of writing the numbers as 16 digits without any whitespace

The code I use

input.value = input.value.replace(/d{4}/g, "$& ");

Bug

After replacing the input.value in format that I want, I can not delete the value unless I click on a specific group of numbers, for example:

input.value is:
"1234 5678 9123 4567 "

Now when I press "Backspace key" on keyboard, it won’t delete the numbers, to do so, I need click on "4567" to be able to delete this group.

How can I fix this?

2

Answers


  1. Chosen as BEST ANSWER

    By adding trim() method, problem was solved

    input.value = input.value.replace(/d{4}/g, "$& ").trim();
    

  2. That bug occurs because your regex have a small issue.

    I recreated the input-text-replacing functionality with your line of code and mine.

    Yours:

    input.addEventListener("input", () => {
        let inputValue = input.value;
    
        inputValue = inputValue.replace(/(d{4})/g, "$& "); // Adding spaces.
    });
    

    Mine:

    input.addEventListener("input", () => {
        let inputValue = input.value;
        
        inputValue = inputValue.replace(/D/g, ""); // Only numbers are allowed.
        inputValue = inputValue.replace(/(d{4})(?=d)/g, "$& "); // Adding spaces.
        
        input.value = inputValue.slice(0, 19); // Limiting to 16 numbers.
    });
    

    Hope this would work!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search