--- title: Assertions slug: Web/JavaScript/Guide/Regular_expressions/Assertions page-type: guide sidebar: jssidebar --- Assertions include boundaries, which indicate the beginnings and endings of lines and words, and other patterns indicating in some way that a match is possible (including look-ahead, look-behind, and conditional expressions). {{InteractiveExample("JavaScript Demo: RegExp Assertions", "taller")}} ```js interactive-example const text = "A quick fox"; const regexpLastWord = /\w+$/; console.log(text.match(regexpLastWord)); // Expected output: Array ["fox"] const regexpWords = /\b\w+\b/g; console.log(text.match(regexpWords)); // Expected output: Array ["A", "quick", "fox"] const regexpFoxQuality = /\w+(?= fox)/; console.log(text.match(regexpFoxQuality)); // Expected output: Array ["quick"] ``` ## Types ### Boundary-type assertions
| Characters | Meaning |
|---|---|
^ |
Input boundary beginning assertion:
Matches the beginning of input. If the Note: This character has a different meaning when it appears at the start of a character class. |
$ |
Input boundary end assertion:
Matches the end of input. If the |
\b |
Word boundary assertion: Matches a word boundary. This is the position where a word character is not followed or preceded by another word-character, such as between a letter and a space. Note that a matched word boundary is not included in the match. In other words, the length of a matched word boundary is zero. Examples:
To match a backspace character ( |
\B |
Non-word-boundary assertion:
Matches a non-word boundary. This is a position where the previous and
next character are of the same type: Either both must be words, or
both must be non-words, for example between two letters or between two
spaces. The beginning and end of a string are considered non-words.
Same as the matched word boundary, the matched non-word boundary is
also not included in the match. For example,
|
| Characters | Meaning |
|---|---|
x(?=y) |
Lookahead assertion:
Matches "x" only if "x" is
followed by "y". For example, |
x(?!y) |
Negative lookahead assertion:
Matches "x" only if "x"
is not followed by "y". For example, |
(?<=y)x |
Lookbehind assertion:
Matches "x" only if "x" is
preceded by "y". For example,
|
(?<!y)x |
Negative lookbehind assertion:
Matches "x" only if
"x" is not preceded by "y". For example,
|