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 ..

0

2 Answers 2

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]+$/;
Sign up to request clarification or add additional context in comments.

Comments

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 Comments

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.
Actually, this expression still matches Mr.Abc., so the answer is incorrect.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.