简体   繁体   English

单引号不会在javascript中替换吗?

[英]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. 我对我的正则表达式非常有信心,并且以前对replace函数没有问题。 Is there a chance that mySQLdb is messing this up? mySQLdb是否有可能将其弄乱? 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");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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