64

I am searching for a regular expression for allowing alphanumeric characters, -, _ or spaces in JavaScript/jQuery.

SagarPPanchal
  • 9,839
  • 6
  • 34
  • 62
rahul
  • 7,573
  • 7
  • 39
  • 53

10 Answers10

107

Character sets will help out a ton here. You want to create a matching set for the characters that you want to validate:

  • You can match alphanumeric with a \w, which is the same as [A-Za-z0-9_] in JavaScript (other languages can differ).
  • That leaves - and spaces, which can be combined into a matching set such as [\w\- ]. However, you may want to consider using \s instead of just the space character (\s also matches tabs, and other forms of whitespace)
    • Note that I'm escaping - as \- so that the regex engine doesn't confuse it with a character range like A-Z
  • Last up, you probably want to ensure that the entire string matches by anchoring the start and end via ^ and $

The full regex you're probably looking for is:

/^[\w\-\s]+$/

(Note that the + indicates that there must be at least one character for it to match; use a * instead, if a zero-length string is also ok)

Finally, http://www.regular-expressions.info/ is an awesome reference


Bonus Points: This regex does not match non-ASCII alphas. Unfortunately, the regex engine in most browsers does not support named character sets, but there are some libraries to help with that.

For languages/platforms that do support named character sets, you can use /^[\p{Letter}\d\_\-\s]+$/

Community
  • 1
  • 1
Nevir
  • 7,951
  • 4
  • 41
  • 50
73

Try this regex:

/^[a-z\d\-_\s]+$/i
elclanrs
  • 92,861
  • 21
  • 134
  • 171
  • 4
    @rahul: This works but check Nevir's answer because it should work too and it's a bit shorter. Basically `\w` means alpha + underscore, it's just a shortcut like `\d` means `[0-9]`. – elclanrs Nov 08 '12 at 06:29
  • 1
    Try this Regex `/^[\w]+([-_\s]{1}[a-z0-9]+)*$/i` This will allow only single space or - or _ between text `Ex: atoz-some word_1234` – kva Jul 05 '19 at 13:53
12
/^[-\w\s]+$/

\w matches letters, digits, and underscores

\s matches spaces, tabs, and line breaks

- matches the hyphen (if you have hyphen in your character set example [a-z], be sure to place the hyphen at the beginning like so [-a-z])

cbayram
  • 2,259
  • 11
  • 9
10
var string = 'test- _ 0Test';
string.match(/^[-_ a-zA-Z0-9]+$/)
nkamm
  • 627
  • 5
  • 14
4
var regex = new RegExp("^[A-Za-z0-9? ,_-]+$");
            var key = String.fromCharCode(event.charCode ? event.which : event.charCode);
            if (!regex.test(key)) {
                event.preventDefault();
                return false;
            }

in the regExp [A-Za-z0-9?spaceHere,_-] there is a literal space after the question mark '?'. This matches space. Others like /^[-\w\s]+$/ and /^[a-z\d\-_\s]+$/i were not working for me.

Daniel Beck
  • 20,653
  • 5
  • 38
  • 53
Asif Khan
  • 71
  • 5
  • This allows basics special characters that needed " ",?,:, .... And blocking others. THanks – Rigin Feb 14 '18 at 21:23
4

Try this regex

*Updated regex

/^[a-z0-9]+([-_\s]{1}[a-z0-9]+)*$/i

This will allow only single space or - or _ between the text

Ex: this-some abc123_regex

To learn : https://regexr.com

*Note: I have updated the regex based on Toto question

kva
  • 486
  • 4
  • 15
  • Why do you want to match single space hyphen or underscore? This is not what it was aked. And your regex [matches `_______`](https://regex101.com/r/BO0cER/1) – Toto Jul 05 '19 at 13:55
  • I have reason for that. Assume that there is a field for username with @elclanrs regex (first answer). In this case an real time user can simply enter `---_ _ _` this in his username field and validation become passed which is toally wrong. So to avoid that i have given regex like that with conditions. – kva Jul 09 '19 at 14:25
  • But your regex matches `____` which is wrong, see the link provided in my previous comment. – Toto Jul 09 '19 at 15:42
  • It allways match `_____ ` (a space at the end). – Toto Jul 11 '19 at 09:41
  • Now no special characters allowed except 'hyphen' and 'underscore' – kva Jul 12 '19 at 12:27
0

For me I wanted a regex which supports a strings as preceding. Basically, the motive is to support some foreign countries postal format as it should be an alphanumeric with spaces allowed.

  1. ABC123
  2. ABC 123
  3. ABC123(space)
  4. ABC 123 (space)

So I ended up by writing custom regex as below.

/^([a-z]+[\s]*[0-9]+[\s]*)+$/i

enter image description here

Here, I gave * in [\s]* as it is not mandatory to have a space. A postal code may or may not contains space in my case.

Sibeesh Venu
  • 18,755
  • 12
  • 103
  • 140
0
var1 regex = new     RegExp1("^[A-Za-z0-9? ,_-]+$");
var1 key = String1.fromCharCode(event1.charCode ? event1.which : event1.charCode);

if (!regex1.test(key)) {
  event1.preventDefault();
  return false;   
}
Tyler2P
  • 2,324
  • 26
  • 22
  • 31
  • 1
    Your answer could be improved by adding more information on what the code does and how it helps the OP. – Tyler2P Jul 08 '22 at 14:43
  • 1
    This answer was flagged as [Low Quality](https://stackoverflow.com/help/review-low-quality), and could benefit from an explanation. Here are some guidelines for [How do I write a good answer?](https://stackoverflow.com/help/how-to-answer). Code only answers are **not considered good answers**, and are likely to be downvoted and/or deleted because they are **less useful** to a community of learners. It's only obvious to you. Explain what it does, and how it's different / **better** than existing answers. [From Review](https://stackoverflow.com/review/low-quality-posts/32203832) – Trenton McKinney Jul 08 '22 at 17:07
-1

Following both are worked for me.

/[^a-zA-Z0-9\-_\s]/g
/[^a-z\d\-_\s]+$/i

Can replace other except alphanumerics, -, _ with empty like this.

inputString.replace(/[^a-zA-Z0-9\-_\s]/g,"");
-1

Try this for allowing alphanumeric and space

[a-zA-Z0-9 ]