In this tutorial, you’ll learn about regular expression anchors that allow you to match a position before or after characters.

Anchors have special meaning in regular expressions. They do not match any character. Instead, they match a position before or after characters:

  • ^ – The caret anchor matches the beginning of the text.
  • $ – The dollar anchor matches the end of the text.

See the following example:

let str = 'JavaScript';
console.log(/^J/.test(str));

Output:

true

The /^J/ match any text that starts with the letter J. It returns true.

The following example returns false because the string JavaScript doesn’t start with the letter S:

let str = 'JavaScript';
console.log(/^S/.test(str));

Output:

false

Similarly, the following example returns true because the string JavaScript ends with the letter t:

let str = 'JavaScript';
console.log(/t$/.test(str));

Output:

true

You will often need to use anchors ^ and $ to check if a string fully matches a pattern.

#javascript #programming #developer #web-development

JavaScript Regular Expressions Tutorial: Regular Expression Anchors
2.30 GEEK