Intro
In the previous three regex blogs we looked for matches regardless of where they were positioned. You can also look for patterns that are at specific positions in the string.
Match patterns at the beginning/end of the string
By using the ^ symbol (called an anchor) you can check if the string starts with a specific pattern:
let str = "Larry played basketball today"
let regex = /^Larry/
regex.test(str) //true
By using the $ symbol (also called an anchor) we can check if the string ends with a specific pattern:
let str = "Larry played basketball today"
let regex = /today$/
regex.test(str) //true
Using both anchors
By using both anchors you can check if a string fully matches a pattern:
let timeIsValid = /^\d\d:\d\d$/.test('12:05');
console.log(timeIsValid); //true
Top comments (1)