Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I replace a backslash with a double backslash using RegExp?

I need to modify the value using javascript, to make it ready to be put as part of a SQL insert query.

Currently I have the following code to handle the single quote ' character.

value = value.replace(/'/g, "\\'");

This code works without an issue. Now I noticed that stand-alone backslashes are causing errors.

How can I remove those stand alone backslashes?

like image 333
user1052933 Avatar asked Dec 30 '11 23:12

user1052933


2 Answers

Now I noticed that stand-alone backslashes are causing errors.

Backslashes in the string you're operating on won't have any effect on replacing ' characters whatsoever. If your goal is to replace backslash characters, use this:

value = value.replace(/\\/g, "whatever");

...which will replace all backslashes in the string with "whatever". Note that I've had to write two backslashes rather than just one. That's because in a regular expression literal, the backslash is used to introduce various special characters and character classes, and is also used as an escape — two backslashes together in a regular expression literal (as in a string) represent a single actual backslash in the string.

To change a single backslash into two backslashes, use:

value = value.replace(/\\/g, "\\\\");

Note that, again, to get a literal backslash in the replacement string, we have to escape each of the two — resulting in four in total in the replacement string.

I need to modify the value using javascript, to make it ready to be put as part of a SQL insert query.

You don't want to do this by hand. Any technology that allows you to make database queries and such (JDBC, ODBC, etc.) will provide some form of prepared or parameterized statement (link), which deals with these sorts of escaping issues for you. Doing it yourself is virtually guaranteed to leave security holes in your software which could be exploited. You want to use the work of a team that's had to think this through, and which updates the resulting code periodically as issues come to light, rather than flying alone. Further, if your JavaScript is running on the client (as most is, but by no means all — I use JavaScript server-side all the time), then nothing you do to escape the string can make it safe, because client requests to the server can be spoofed, completely bypassing your client-side code.

like image 92
T.J. Crowder Avatar answered Oct 14 '22 11:10

T.J. Crowder


You should use a escape function provided by some kind of database library, rolling your own will only cause trouble.

like image 30
Mattias Wadman Avatar answered Oct 14 '22 09:10

Mattias Wadman