简体   繁体   中英

javascript RegEx checking for any letters in string (needs to ignore other glyphs though - so not just 0-9)

I need to test a string that will potentially have numbers, letters, dashes, forward slashes and other glyphs in it. Only numbers, dashes and forward slashes should be allowed. Tried a couple times but I keep getting the regex syntax wrong.

Basically:

var str = '03/02/2013'; //03-02-2013 is also acceptable 

if(str has letters in it){
  console.log('incorrect formatting');
}else{
  //string is made up of only numbers, dashes or forward slashes
  console.log('okay');
}

如果要检查字符串“仅由数字,破折号或正斜杠组成” ,则可以使用以下命令:

var isOK = /^[\d\-\/]*$/.test(str)

Is it a date format ? You could try

var str="10/12/2012"; 
var n=/^[0-9]{2}[\/-][0-9]{2}[\/-][0-9]{4}$/.test(str);

If you want to test if the string only contains numbers, dashes and forward slashes, this should do the trick:

var EXP = /^[\d-\/]+$/;

This would match a string og any length with any number of any of the allowed characters. If you explicity want to make sure that the string conforms to a date format where both dashes and forward slashes:

var EXP = /^\d{1,2}[\/-]\d{1,2}[\/-]\d{1,4}$/;

This would match a date format that allows one or two digits for day and month and 2-4 digits for year, separated by dashes or forward slashes.

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