简体   繁体   中英

Why doesn't the following JavaScript Regular Expression work?

The Above Regular Expression Question was featured on HackerRank ,It should return true if string contains Mr./Mrs./Ms./Dr./Er. in the beginning followed by group of letters.

For Eg: Mr.Abc is true but Mr.Abc. isn't But my code returns Mr.Abc. as true.

 let inp="Mr.Abc."; let re=new RegExp(/^Mr\\.|^Ms\\.|^Mrs\\.|^Dr\\.|^Er\\.[A-Za-z]/); console.log(re.test(inp));

PSSorry for my Bad Regular Expression statement i'm currently in the learning stage ..

It's a grouping problem, as well as an issue with the fact that you don't test for the end of the string using $ . Using your expression, Mr.Abc. returns true because it matches ^Mr\\.

Change your expression as follows:

let re = /^(Mr|Ms|Mrs|Dr|Er)\.[A-Za-z]+$/;

I tried the same thing and it resolved this issue with this simple change.

let re = new RegExp(/^Mr\.|^Ms\.|^Mrs\.|^Dr\.|^Er\.[A-Za-z]*$/);

This would make the search stringent while checking the string. Hope this helps :)

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