Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Backspace \b not working when included in alphabetic regex in JS

The following blocks out all chars which are not either alphabetic or backspace (\b), but you can see that the Backspace doesn’t work and is also filtered out. Why is that?

$('#field').keydown(function(e) {
  if (!/^[A-Za-z\b]$/i.test(e.key)) {
    e.preventDefault();
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="text" id="field" />

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The event.key value for the backspace key is "Backspace".

$('#field').keydown(function(e) {
  if (!/^([a-z]|Backspace)$/i.test(e.key)) {
    e.preventDefault();
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="field" />
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading