Anchors string start and end $
On this page
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. (在JavaScript中,锚点是插入符号^和美元$字符,在正则表达式中具有特定含义。插入符号对应于文本的开头和结尾的美元。)
For example, let’s check whether the text begins with Welcome:
let str1 = "Welcome to w3cdoc";
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 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. (在这种情况下,可以使用字符串方法,如startsWith/endsWith。更复杂的测试需要使用正则表达式。)
Testing for a Full Match
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. (当有标志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. (最后,锚点的宽度为零,因为它们是测试。这意味着它们不对应于字符,并强制正则表达式引擎检查条件。)