1

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));

P.S.Sorry for my Bad Regular Expression statement i'm currently in the learning stage ..

Community
  • 1
  • 1
Shardul Birje
  • 341
  • 5
  • 14

2 Answers2

6

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]+$/;
Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156
1

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 :)

  • 2
    It might work for the specific case, but not for all cases. For example, your expression will also return true for the strings `Mr.`, `Dr.123`, and a whole lot of other cases that should not be matched. – Robby Cornelissen Dec 25 '19 at 08:00
  • 1
    Actually, this expression still matches `Mr.Abc.`, so the answer is incorrect. – Robby Cornelissen Dec 25 '19 at 08:04