^ and $ anchors should be placed properly in a regular expression

  • Error
  • Medium
  • No tags

This rule applies when ^ and $ anchors are not placed properly in a regular expression.

^ and $ are special anchor characters that match the beginning and the end of input.

If ^ appears after matching some input characters, it will always fail to match. Similarly, nothing will be matched after the $ anchor.

Often this alarm occurs when the intention is matching the ^ or $ character itself. In that case, \^ or \$ should be used instead.

Note: Not applied when only one character exists around the ^ or $ because it is often used to intentionally construct an unmatchable pattern like /x^/ or /$x/.

Noncompliant Code Example

View with compliant examples side by side
// Example 1
var re1 = /(foo|bar)^/; // MISPLACED_ANCHOR_IN_REGEXP alarm because '^' is used instead of '$'.

// Example 2
var re2 = /$(foo|bar)/; // MISPLACED_ANCHOR_IN_REGEXP alarm '$' is not properly escaped.

Compliant Code Example

View with noncompliant examples side by side
// Example 1
var re1 = /(foo|bar)$/;

// Example 2
var re2 = /\$(foo|bar)/;


This rule was introduced in DeepScan 1.30.0.


Was this documentation helpful?