只是一个字符串。每次有单引号时添加 \' 。
134066 次
8 回答
73
replace
适用于第一个引号,因此您需要一个很小的正则表达式:
str = str.replace(/'/g, "\\'");
于 2010-02-03T21:26:29.290 回答
39
以下 JavaScript 函数处理 '、"、\b、\t、\n、\f 或 \r 等价于 php 函数 addlashes()。
function addslashes(string) {
return string.replace(/\\/g, '\\\\').
replace(/\u0008/g, '\\b').
replace(/\t/g, '\\t').
replace(/\n/g, '\\n').
replace(/\f/g, '\\f').
replace(/\r/g, '\\r').
replace(/'/g, '\\\'').
replace(/"/g, '\\"');
}
于 2012-07-30T06:24:59.903 回答
22
使用 JSON.stringify 可以全面而紧凑地转义字符串。从ECMAScript 5开始,它是 JavaScript 的一部分,并被主要的较新浏览器版本支持。
str = JSON.stringify(String(str));
str = str.substring(1, str.length-1);
使用这种方法,空字节、unicode 字符和换行符\r
等特殊字符也可以\n
在相对紧凑的语句中正确转义。
于 2014-02-13T16:52:20.500 回答
5
可以肯定的是,您不仅需要替换单引号,还需要替换已经转义的单引号:
"first ' and \' second".replace(/'|\\'/g, "\\'")
于 2010-02-03T21:32:42.880 回答
4
如果您正在做替换以准备将字符串发送到 alert() 或任何其他单引号字符可能会绊倒您的地方,那么您没有要求的答案可能会有所帮助。
str.replace("'",'\x27')
这将用单引号的十六进制代码替换所有单引号。
于 2010-02-03T21:59:34.673 回答
3
var myNewString = myOldString.replace(/'/g, "\\'");
于 2010-02-03T21:25:50.337 回答
2
var str = "This is a single quote: ' and so is this: '";
console.log(str);
var replaced = str.replace(/'/g, "\\'");
console.log(replaced);
给你:
This is a single quote: ' and so is this: '
This is a single quote: \' and so is this: \'
于 2010-02-03T21:27:09.693 回答
2
if (!String.prototype.hasOwnProperty('addSlashes')) {
String.prototype.addSlashes = function() {
return this.replace(/&/g, '&') /* This MUST be the 1st replacement. */
.replace(/'/g, ''') /* The 4 other predefined entities, required. */
.replace(/"/g, '"')
.replace(/\\/g, '\\\\')
.replace(/</g, '<')
.replace(/>/g, '>').replace(/\u0000/g, '\\0');
}
}
用法:alert(str.addSlashes());
于 2016-09-05T19:01:44.013 回答