Include backspace in Regex with textarea

Viewed 152

I have looked at this post to help me (regular expression in javascript which allows backspace), but still, I can not use my backspace to delete characters.

I have tried different variations with

(/[0-1,\b]/g) 
(/[0-1][\b]/g)
(/[0-1]+[\b]/g)


...nothing is working.

Here is my whole function:

binary.addEventListener('keydown', (event) => {
  if (event.key.match(/[0-1]/g)) {
    return event;
  } else {
    event.preventDefault();
  }
});

Event handler is attached to <textarea id="binary" placeholder="Binary..." type="text"></textarea>.

I have tried to remove preventDefault(), but my regex does not apply then.

1 Answers

You can check if BACKSPACE is pressed by adding a event.keyCode === 8 || alternative to the if condition.

Also, it is probably "cleaner" to use RegExp.test() to check if a regex matches a string, /[01]/.test(event.key).

let log  = document.querySelector('#log'),
    test = document.querySelector('#test');

test.addEventListener('keydown', (event) => {
  if (event.keyCode === 8 || /[01]/.test(event.key)) {
    return event;
  } else {
    event.preventDefault();
  }
});
#test:focus{outline: none;}
<input type='text' id='test' autofocus /><br />
<span id='log'></span>

Related