Beginning Of String Anchor – ‘^’


You can constrain that a match for a pattern must be found at the beginning of the string being searched with the caret '^' symbol. If you want to match ‘Humpty’ at the beginning of string, you can use the pattern /^Humpty/. Note that the caret symbol must be the first character in the pattern.

let wordPttn = /^Humpty/;
let targetString = "Humpty Dumpty sat on a wall";
let result = targetString.match(wordPttn);
console.log((result !== null ?
`Pattern ${wordPttn} FOUND in '${targetString}'. Matched string is '${result[0]}'`
: `Pattern ${wordPttn} NOT FOUND in '${targetString}'`));
targetString = "Dumpty Humpty sat on a wall";
result = targetString.match(wordPttn);
console.log((result !== null ?
`Pattern ${wordPttn} FOUND in '${targetString}'. Matched string is '${result[0]}'`
: `Pattern ${wordPttn} NOT FOUND in '${targetString}'`));

Output:

Pattern /^Humpty/ FOUND in 'Humpty Dumpty sat on a wall'. Matched string is 'Humpty'
Pattern /^Humpty/ NOT FOUND in 'Dumpty Humpty sat on a wall'

If the 'm' flag is set, the JavaScript regex engine tries to find a match at the beginning of each line apart from the beginning of the string.

let wordPttn = /^[Tt]he/gm;
let targetString = "The ball is in your court. \nThe best of both worlds. "
+ "\nAt the end of your rope "
+ "\nThe whole nine yards \nAt the drop of a hat";
let results = targetString.matchAll(wordPttn);
for (let result of results) {
console.log((result !== null ?
`Pattern ${wordPttn} FOUND at '${result.index}'. Matched string is '${result[0]}'`
: `Pattern ${wordPttn} NOT FOUND in '${targetString}'`));
}

Output:

Pattern /^[Tt]he/gm FOUND at '0'. Matched string is 'The'
Pattern /^[Tt]he/gm FOUND at '28'. Matched string is 'The'
Pattern /^[Tt]he/gm FOUND at '79'. Matched string is 'The'

Apart from specifying the match at the beginning of a string, the caret '^' symbol has other context specific meanings in regular expressions –

  • If the ^ symbol appears as the first character in a character class (eg [^pqr]), it indicates negation
  • If the ^ symbol appears in the middle of a character class (eg [pq^r]), it is a literal match for itself
  • If the ^ symbol appears in the middle of a pattern outside a character class (eg /abc^zyz/), the pattern will not match