Anchors: string start ^ and end $
For example, let’s check whether the text begins with Welcome:
let str1 = "Welcome to W3Docs"; console.log(/^Welcome/.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 describe above are also used together ^...$ for testing whether the string completely matches the pattern or not.
Let’s try to test whether the 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.