简体   繁体   中英

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.

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,\-. ]*$/;
var letters = /^[a-zA-Z0-9\-\,. ]+$/;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM