Mary
Mary

Reputation: 1595

javascript- regular expression alphanumeric and special characters

I am trying to allow alphanumeric and some special characters

var regx = /^[A-Za-z0-9._-\] ]+$/;

I tried escaping the ] sign with the forward slash but it still doesnt work. What am I missing

Upvotes: 1

Views: 450

Answers (2)

Federico Piazza
Federico Piazza

Reputation: 31035

If you try your regex on an online regex tester like regex101 you'd get the error:

Regex link

enter image description here

You have to escape - using \-:

^[A-Za-z0-9._\-\] ]+$

Btw, you can shorten your regex to:

^[\w.\-% ]+$

Edit: added regex for your comment:

^[\w.-\]\[ #$>()@{}'"]+$

Working demo

Upvotes: 1

Salman Arshad
Salman Arshad

Reputation: 272436

You also need to escape the - character:

/^[A-Za-z0-9._\-\] ]+$/
//------------^

Escaping - is not always necessary. Here, however, it is used inside square brackets which makes the JavaScript engine assume that you are trying to specify the range from _-] which causes a "Range out of order in character class" error.

Note that /[_-a]/ is valid regex and matches characters _, ` and a (ASCII codes 95...97); which may not be the desired outcome.

Upvotes: 4

Related Questions