The general rule is that any tricky security code should have as many eyeballs on it as possible, so I&#x27;d probably start by seeing if my framework had solid support for this, or failing that, see what popular libraries for my platform exist.<p>In this particular case, the Google Caja project[1] is a good starting place for most HTML&#x2F;JS&#x2F;CSS sanitization needs (although the project has a much larger scope than <i>just</i> that); and I think the &#x27;sanitizer&#x27; package on npm is a fairly popular wrapper&#x2F;port of it&#x27;s basic sanitizing code, and I believe ruby&#x2F;php&#x2F;python have their own but I couldn&#x27;t name them offhand.  But it would depend on the exact attack vector you&#x27;re trying to stop, eg, XSS, remote shell via filename params, etc.<p>If I had to write it myself, I&#x27;d probably go for something as braindead as possible; probably a bunch of nested loops backed by some thorough tests.  Regexps are great for magic one liners, but magic one liners are antithetical to good security.<p>[1]: <a href="https:&#x2F;&#x2F;developers.google.com&#x2F;caja&#x2F;" rel="nofollow">https:&#x2F;&#x2F;developers.google.com&#x2F;caja&#x2F;</a>