Jason Knight
1 min readJul 29, 2020

--

An EXCELLENT point! Careful what you plug into your regex!

It’s excellent advice ANY time you have a variable where the value came from user-side regardless of what you’re doing with it. SQL, noSQL, regex, part of your server-side include() name, it doesn’t matter. Escape/sanitize EVERY time or it will bite you sooner than later!

As such it helps to either regex escape your strings, or only use it where you know what you're plugging in didn't come from the user.

Hence why I usually have this or something similar handy:

function rxEscape(text) {
return text.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
} // rxEscape

Though it sucks to have to regex before a regex, at least you can be reasonably certain what you’re doing is safe.

--

--

Jason Knight
Jason Knight

Written by Jason Knight

Accessibility and Efficiency Consultant, Web Developer, Musician, and just general pain in the arse

No responses yet