简体   繁体   中英

Single quotes not being replaced in javascript?

I'm trying to sanitize quotes from a text input. Right now my code is:

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

My out put has all double quotes replaced, but the single quotes remain. I am fairly confident in my regex, and haven't had a problem with the replace function before. Is there a chance that mySQLdb is messing this up? I am posting it and then getting almost immediately after. This seems like such a simple issue but it really has me stumped

Your replacements are null operations since the backslash is consumed by the string literal itself and is not present in the actual string value.

Instead escape the backslash to really get one in your string:

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

You can of course do this in one operation:

string = string.replace(/(['"])/g, "\\$1");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM