Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
546 views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...