简体   繁体   中英

javascript regex is failing to match a given string

This Meteor code is failing to match the regex to the string and produce true in the if conditional statement. What am I doing wrong? how to fix it? Thanks

 console.log(doc.valid); console.log(doc.value); var patt = new RegExp(doc.valid); console.log(patt); if (patt.test(doc.value)) { console.log("match"); } else { console.log("no match"); } 
 //meteor terminal I20160313-08:06:53.143(11)? /[0-9a-zA-Z]{1,6}/g I20160313-08:06:53.144(11)? ok I20160313-08:06:53.144(11)? //[0-9a-zA-Z]{1,6}/g/ I20160313-08:06:53.145(11)? no match 

edited applied the fix as suggested in the comments but the regex matches a string which is not suppose to match.

 var patt = new RegExp(doc.valid); console.log('applying '+ patt+ ' to '+ doc.value); if (patt.test(doc.value, "g")) { console.log(doc.value + " match"); } else { console.log(doc.value + "no match"); } I20160313-08:48:26.717(11)? applying /[0-9a-zA-Z]{1,6}/ to Kingkong I20160313-08:48:26.717(11)? Kingkong match <..8 char.not suppose to match 

If you want your regular expression to mean "match an alphanumeric string with strictly 1 to 6 letters (but not more)", then it should be:

/^[0-9a-zA-Z]{1,6}$/

the original:

/[0-9a-zA-Z]{1,6}/

means "match an alphanumeric string which contains a substring of 1 to 6 letters". The test string "Kingkong" clearly matches that rule.

I think your problem lies in the way that you try to instantiate the RegExp object. The RegExp object accepts as first argument a string and not a regex. Try new RegExp("[0-9a-zA-Z]{1,6}","g")

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