DEV Community

SCDan0624
SCDan0624

Posted on

Javascript regex part 4 searching for patterns in specific positions

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
bugb profile image
bugb • Edited
const timeIsValid = /^\d{2}:\d{2}$/.test('12:05');
// Or it is better: const timeIsValid = /^([0-1][0-9]|2[0-3]):[0-5][0-9]$/;
console.log(timeIsValid); //true
Enter fullscreen mode Exit fullscreen mode