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

情到浓时终转凉″ 提交于 2019-12-18 03:35:18

问题


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?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/8684975/how-can-i-replace-a-backslash-with-a-double-backslash-using-regexp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!