Anchors and Boundaries
Understanding Anchors
Anchors are special characters in Regex that match positions in a string rather than actual characters. They are useful for specifying where a match must occur in the string.
Common Anchors
^
: Matches the start of a string$
: Matches the end of a string
Example: Using Anchors
Let’s look at some examples of how these anchors work:
- Caret (
^
) Anchor
const regexStart = /^hello/;
console.log(regexStart.test('hello world')); // true (matches 'hello' at the start)
console.log(regexStart.test('world hello')); // false (no match because 'hello' is not at the start)
- Dollar Sign (
$
) Anchor
const regexEnd = /world$/;
console.log(regexEnd.test('hello world')); // true (matches 'world' at the end)
console.log(regexEnd.test('world hello')); // false (no match because 'world' is not at the end)
Combining Anchors
You can combine ^
and $
to match an exact string:
const regexExact = /^hello world$/;
console.log(regexExact.test('hello world')); // true (matches the entire string)
console.log(regexExact.test('hello')); // false (no match because the entire string does not match)
console.log(regexExact.test('world hello')); // false (no match because the entire string does not match)
Word Boundaries
Word boundaries \b
are used to match positions where a word starts or ends. They are useful for matching whole words.
\b
: Matches a word boundary\B
: Matches a non-word boundary
Example: Using Word Boundaries
- Word Boundary (
\b
)
const regexWordBoundary = /\bhello\b/;
console.log(regexWordBoundary.test('hello world')); // true (matches 'hello' as a whole word)
console.log(regexWordBoundary.test('say hello!')); // true (matches 'hello' as a whole word)
console.log(regexWordBoundary.test('helloworld')); // false (no match because 'hello' is not a whole word)
- Non-Word Boundary (
\B
)
const regexNonWordBoundary = /\Bworld\B/;
console.log(regexNonWordBoundary.test('helloworld')); // true (matches 'world' within a word)
console.log(regexNonWordBoundary.test('hello world')); // false (no match because 'world' is not within a word)
Exercises
- Write a regular expression that matches a string starting with the word “JavaScript”.
- Create a Regex pattern that matches a string ending with the word “developer”.
- Write a regular expression that matches the word “code” as a whole word.
Anchors and boundaries are essential for specifying the position of matches within strings and ensuring that your patterns match exactly what you intend.