Anchors
Regular Expressions: Anchors
What do the caret ^ and dollar sign $ represent in regular expressions?
View Answer:
Interview Response: The caret ^ and dollar $ characters have special meaning in a regexp. They are called \u201Canchors\u201D. The caret ^ matches at the beginning of the text, and the dollar $ represents the end. You should note that we could use the startsWith and endsWith methods to perform the same task, which is the recommendation. We use regular expressions for more complex tests in JavaScript.
Code Example:
let str1 = 'Mary had a little lamb';
alert(/^Mary/.test(str1)); // true
let str2 = "it's fleece was white as snow";
alert(/snow$/.test(str2)); // true
What approach should we use to test for a full match in RegExp?
View Answer:
Interview Response: Both anchors, caret, and dollar sign, together ^...$ often get used in testing whether a string fully matches the pattern. For instance, check if the user input is in the proper format.
Code Example:
let goodInput = '12:34';
let badInput = '12:345';
let regexp = /^\d\d:\d\d$/;
alert(regexp.test(goodInput)); // true
alert(regexp.test(badInput)); // false
What does it mean that Anchors (caret/dollar sign) have zero width?
View Answer:
Interview Response: They do not match a character but instead force the regexp engine to check the condition (text start/end).