Day 7: Regular Expressions II Solution
Hello Friends in this article i am gone to share Hackerrank 10 days of javascript solutions with you. | Day 7: Regular Expressions II Solution.
Also visit this link:ย Day 7: Regular Expressions I Solution
Day 7: Regular Expressions II Solution
Task
Complete the function in the editor below by returning aย RegExpย object,ย re, that matches any stringย sย satisfying both of the following conditions:
- Stringย sย starts withย the prefixย Mr.,ย Mrs.,ย Ms.,ย Dr., orย Er.
- The remainder of stringย sย (i.e., the rest of the string after the prefix) consists of one or more upper and/or lowercase English alphabetic letters (i.e.,ย [a-z]ย andย [A-Z]).
Constraints
- The length of stringย sย isย =>3.
Output Format
The function must return aย RegExpย object that matches any stringย sย satisfying both of the given conditions.
Sample Input 0
Mr.X
Sample Output 0
true
Explanation 0
This string starts withย Mr., followed by an English alphabetic letter (X).
Sample Input 1
Mrs.Y
Sample Output 1
true
Explanation 1
This string starts withย Mrs., followed by an English alphabetic letter (Y).
Sample Input 2
Dr#Joseph
Sample Output 2
false
Explanation 2
This string starts withย Dr#ย instead ofย Dr., so itโs invalid.
Sample Input 3
Er .Abc
Sample Output 3
false
Explanation 3
This string starts withย Erย but there is a space before the period (.), making the string invalid.
Solution โ Day 7: Regular Expressions II
'useย strict'; process.stdin.resume(); process.stdin.setEncoding('utf-8'); letย inputStringย =ย ''; letย currentLineย =ย 0; process.stdin.on('data',ย inputStdinย =>ย { ย ย ย ย inputStringย +=ย inputStdin; }); process.stdin.on('end',ย _ย =>ย { ย ย ย ย inputStringย =ย inputString.trim().split('\n').map(stringย =>ย { ย ย ย ย ย ย ย ย returnย string.trim(); ย ย ย ย }); ย ย ย ย ย ย ย ย main();ย ย ย ย }); functionย readLine()ย { ย ย ย ย returnย inputString[currentLine++]; } functionย regexVar()ย { ย ย ย ย /* ย ย ย ย ย *ย Declareย aย RegExpย objectย variableย namedย 're' ย ย ย ย ย *ย Itย mustย matchย aย stringย thatย startsย withย 'Mr.',ย 'Mrs.',ย 'Ms.',ย 'Dr.',ย orย 'Er.',ย ย ย ย ย ย *ย followedย byย oneย orย moreย letters. ย ย ย ย ย */ ย ย ย ย letย reย =ย /^(Mr|Mrs|Ms|Dr|Er)(\.)([a-zA-Z])+$/; ย ย ย ย /* ย ย ย ย ย *ย Doย notย removeย theย returnย statement ย ย ย ย ย */ ย ย ย ย returnย re; } functionย main()ย { ย ย ย ย constย reย =ย regexVar(); ย ย ย ย constย sย =ย readLine(); ย ย ย ย ย ย ย ย console.log(!!s.match(re)); }