Explain Codes LogoExplain Codes Logo

Is there a RegExp.escape function in JavaScript?

javascript
regex
javascript-features
security
Anton ShumikhinbyAnton Shumikhin·Oct 29, 2024
TLDR
const escapeRegExp = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // because regex needs some peace, too

Use escapeRegExp with your string to escape RegExp special characters. This prevents them from crashing the RegExp party as pattern tokens—a guaranteed way towards meaningful relationships with regex.

DIY escape function

In a world where a standard RegExp.escape is still a dream, creating a custom escape function is our go-to pragmatic approach. It's like a DIY project, only nobody gets accidentally glued to the floor.

The above function carefully mops up all special characters—even the ones that don't play well like ^, $, and -—sends them to a special character reform school (by replacing them with their escaped versions), and then reintroduces them back into the regex society.

And if DIY's not your jam, lasso the off-the-shelf _.escapeRegExp function from Lodash, proving you don't have to reinvent the wheel to keep rolling.

Regex bodyguard

The escape function is your regex bodyguard, keeping all the troublemaking characters in check. With it watching the door, characters like - and / involved in range-setting and delimiter-setting shenanigans are quickly set straight.

/[-[\]{}()*+?.,\\^$|#\s]/g

"I'm the regex nightclub bouncer, - is suspiciously looking around inside character classes, and / has trouble written all over it!"

Future regex, today

The JavaScript we speak today uses certain special characters, but who knows what the future of JavaScript holds? A well-armed regex escape function that's ready for tomorrow keeps your conscience clean and regex tidy.

Creating a regExpEscapeFuture function is like building a spaceship—there might be new stars (special characters) to escape in the future, so why not dream big?

Processing user input

Regex without an escape mechanism is like a kitchen without a fire extinguisher—risky business. Processing user input securely is as important as making a regex pattern that works.

The escape function rolls out a red carpet for incoming user content, ensuring that beautiful patterns are painted on the regex canvas without fear of unexpected syntax graffiti.

When context is king

CharacterSetPrince: "Hyphen, why do you always range?"

Hyphen: "That's how I class apart!"

Backslashes, meanwhile, like to party in pairs within strings. With double escaping, we ensure they stick to their literal nature—unlike their singleton siblings.

Anticipating the possible promotion of minor characters (like # or =) to special characters in future ECMAScript updates, escaping them now makes your code a real trendsetter.

A standard missed?

No native RegExp.escape in JavaScript? It's like a pizza without extra cheese—a standard missed. As JavaScript continues its developmental journey, including RegExp.escape could well be the extra topping everyone relishes.

In the meantime, community-led solutions like Lodash and custom functions help satisfy our regex cravings, toast to JavaScript's collaborative spirit!