Symbol.match, matchAll, replace, and search
What you'll learn: How to make custom objects work like regular expressions by implementing symbols that power JavaScript's built-in string search methods.
Why These Symbols Exist
When you call str.match(regex) or str.replace(regex, replacement), JavaScript doesn't just check if the second argument is a regex—it checks if the object has certain well-known symbols. This means you can create custom objects that behave like pattern matchers without actually being RegExp instances.
The Four String Method Symbols
Symbol.match
Called by String.prototype.match(). Return an array-like result or null.
const matcher = {
[Symbol.match](str) {
return str.includes('hello') ? ['hello'] : null;
}
};
'say hello'.match(matcher); // ['hello']
'goodbye'.match(matcher); // null
Symbol.matchAll
Called by String.prototype.matchAll(). Should return an iterator of match objects.
const multiMatcher = {
[Symbol.matchAll](str) {
const matches = [];
let index = 0;
while ((index = str.indexOf('a', index)) !== -1) {
matches.push(['a']);
index++;
}
return matches[Symbol.iterator]();
}
};
[...'banana'.matchAll(multiMatcher)]; // [['a'], ['a'], ['a']]
Symbol.replace
Called by String.prototype.replace(). Return the modified string.
const replacer = {
[Symbol.replace](str, replacement) {
return str.split(' ').join(replacement);
}
};
'hello world'.replace(replacer, '-'); // 'hello-world'
Symbol.search
Called by String.prototype.search(). Return the position or -1.
const searcher = {
[Symbol.search](str) {
return str.indexOf('x');
}
};
'abxcd'.search(searcher); // 2
Key Takeaway: By implementing Symbol.match, Symbol.matchAll, Symbol.replace, and Symbol.search on an object, you can create custom pattern matchers that integrate seamlessly with JavaScript's string methods, giving you regex-like behavior without actual regular expressions.