Anchors: string start ^ and end $
In JavaScript, the anchors are the caret ^ and the dollar $ characters, having a specific meaning in a regular expression. The caret corresponds at the beginning of the text and the dollar- at the end.
For example, let’s check whether the text begins with Welcome:
let str1 = "Welcome to Web";
console.log(/^Welcome/.test(str1)); // true
The pattern ^Welcome means that the string starts and then Sarah. In another example, let’s check whether the text ends with a star using book$, like this:
let str1 = "it's Javascript book";
console.log(/book$/.test(str1)); // true
In such cases, string methods such as startsWith/endsWith can be used instead. More complex tests require using regular expressions.
Testing for a Full Match¶
The anchors described above are also used together ^...$ for testing whether the string completely matches the pattern or not.
Let’s try to test whether a string is a time in 13:54 format or not.
Checking that in the language of regexp will look like this:
let goodInput = "13:54";
let badInput = "13:546";
let regexp = /^\d\d:\d\d$/;
console.log(regexp.test(goodInput)); // true
console.log(regexp.test(badInput)); // false
In the example above, the match for \d\d:\d\d should begin after the start of the text ^, and then the end ^ should follow at once.
The behavior of the anchors is different when there is the flag m.
And, finally, the anchors have zero width, as they are tests. It means that they don’t correspond to a character, and force the regexp engine to check the condition.
0 Comments
CAN FEEDBACK
Emoji