Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to allow spaces in alphanumeric

Tags:

jquery

I have this here:

$("#MyInputBox").keypress(function (e) {
  if (e.charCode != 0) {
    var regex = new RegExp("^[a-zA-Z0-9\-\s]+$");
    var key = String.fromCharCode(!e.charCode ? e.which : e.charCode);
    if (!regex.test(key)) {
      e.preventDefault();
      return false;
    }
  }
});

Problem is, it does not allow me to enter a space. I WANT it to allow a space. Everything else works fine (i.e I can enter numbers, letters, dash... but not a space.)

like image 790
Ahmed ilyas Avatar asked Oct 22 '13 00:10

Ahmed ilyas


People also ask

Is space allowed in alphanumeric?

Alphanumeric characters by definition only comprise the letters A to Z and the digits 0 to 9. Spaces and underscores are usually considered punctuation characters, so no, they shouldn't be allowed.

Are spaces allowed in regex?

Yes, also your regex will match if there are just spaces. My reply was to Neha choudary's comment. @Pierre Three years later -- I came across this question today, saw your comment; I use regex hero (regexhero.net) for testing regular expressions.

How do you indicate a space in regex?

The most common forms of whitespace you will use with regular expressions are the space (␣), the tab (\t), the new line (\n) and the carriage return (\r) (useful in Windows environments), and these special characters match each of their respective whitespaces.

How do you write alphanumeric in regex?

The regex \w is equivalent to [A-Za-z0-9_] , matches alphanumeric characters and underscore.


1 Answers

You must escape the backslash before the s

var regex = new RegExp("^[a-zA-Z0-9\\-\\s]+$");

or ommit the constructor:

var regex = /^[a-zA-Z0-9\-\s]+$/
like image 108
Dr.Molle Avatar answered Oct 21 '22 10:10

Dr.Molle