Anirudh Dutta Gupta
Anirudh Dutta Gupta

Reputation: 21

Regular expression in javascript trouble with hyphen

I am new to regular expressions and am having trouble setting one up. What I want is to allow only alphabets, numbers, commas, periods and hyphens. This is what I got:

var letters = /^[a-zA-Z0-9,. ]*$/;

I am having trouble figuring out how to include the hyphen. Please assist.

Upvotes: 0

Views: 53

Answers (2)

Guilherme Fidelis
Guilherme Fidelis

Reputation: 1020

var letters = /^[a-zA-Z0-9\-\,. ]+$/;

Upvotes: 0

Guffa
Guffa

Reputation: 700152

You can include the minus where it won't be interpreted as a range:

var letters = /^[-a-zA-Z0-9,. ]*$/;

You can also use backslash to specify that it's a literal character:

var letters = /^[a-zA-Z0-9,\-. ]*$/;

Upvotes: 1

Related Questions