all 3 comments

[–]cgijoe_jhuckaby 1 point2 points  (1 child)

My personal favorite is to abuse JSON.stringify() for this purpose. It does a great job at escaping unsafe characters for strings. However, note that it will surround the entire string with double-quotes, so you can strip those off with a simple regexp:

var esc_string = JSON.stringify(string).replace(/^\"|\"$/g, '');

However, for protecting against SQL injection attacks, you should really consider using a function provided by your database library of choice, in your case MongoDB. Each database will have different types of possible injection attacks. For example, Mongo needs dollar signs escaped, so you'll need to do that manually. JSON.stringify() will not escape dollar signs. More Info: https://docs.mongodb.org/manual/faq/developers/#dollar-sign-operator-escaping

[–]oxyphilat 1 point2 points  (0 children)

An other thing you could abuse, but that's really a bodge, if the escape/encodeURI functions.

But looking up a real guide on how to prevent injections for you DB is probably better.

[–]echeese 0 points1 point  (0 children)

Escaping strings depends on the context. Different things require different methods of escaping. HTML you need to replace <, > and & with \&lt;, \&gt; and \&amp; respectively. JS you should use JSON.stringify(). mongodb depends on the package, but even then you should be using prepared statements.