显然,当您自己创建一个实际的字符串文字时,反斜杠将自己转义双引号。
var foo = "baz\"bat";
就像你和其他一些控制字符一样,比如换行符和反斜杠。
var bar = "baz\\bat\nmynew line and a \"quote\" ";
但是,如果您只是用引号字符包装现有的变量(即将其提供给需要引用输入的其他系统),则会出现一些混淆。
显然,您必须转义字符串中的任何潜在双引号字符。
var doubleQuoteRe = /\"/g;
var quoted = "\"" + unquoted.replace(escaper, '\\\"') + "\"";
但是据一些人说,您现在还必须担心在变量中转义文字反斜杠字符。换句话说,用比我的小槌大得多的锤子。然而,我不明白为什么。
发布于 2010-03-08 22:20:53
你可能要避免逃避你已经逃过的引号-
String.prototype.inquotes=function(){
return '"'+this.replace(/(^|[^\\])"/g,'$1\\"')+'"';
}
发布于 2010-03-08 21:46:01
答案是肯定的,你必须做两件事:
对于为什么步骤1是必需的,最简单的解释是考虑5-字符字符串:
foo\"
在前3个字符(foo)之后,字符串中有一个文字反斜杠字符,然后有一个文字双引号字符。
(换句话说,作为字符串文本,它看起来应该是“foo\”)
如果我只替换引号字符,我将得到一个引号字符串,其值为
foo\\"
但是这里的两个反斜杠将被解释为一个反斜杠。因此,当我用引号包装这个值时,我会得到不平衡的引号。
"foo\\""
另一方面,如果我先做第一步--用双反斜杠替换所有反斜杠
foo\\"
然后步骤2-用斜杠替换引号
foo\\\"
现在,当我用引号字符包装我的值时,我终于得到了
"foo\\\""
这是正确的。
发布于 2014-09-30 17:30:22
在FF中有一个非标准的str.quote()
对象/字符串/引号他们建议采用以下的填充方式
if(!String.prototype.quote){
// oop version - no dependencies
String.prototype.quote = (function(){
// prepare fallback
// ----------------
// backslash escape double quotes and backslashes
var escp_regex = /[\\"]/g,
escp_callback = '\\$&',
// escape control characters
ctrl_map = {
'\b': '\\b', // backspace
'\t': '\\t', // tab
'\n': '\\n', // new line
'\f': '\\f', // form feed
'\r': '\\r' // carriage return
},
// don't rely on `Object.keys(ctrl_map).join('')`
ctrl_regex = new RegExp('[\b\t\n\f\r]', 'g'),
ctrl_callback = function(match){
return ctrl_map[match];
},
// hex-escape, spare out control characters and ASCII printables
// [0-7,11,14-31,127-255]
xhex_regex = /[\x00-\x07\x0B\x0E-\x1F\x7F-\xFF]/g,
xhex_callback = function(match, char_code){
char_code = match.charCodeAt(0);
return '\\x' + (char_code < 16 ? '0' : '') + char_code;
},
// hex-escape all others
uhex_regex = /[\u0100-\uFFFF]/g,
uhex_callback = function(match, char_code){
char_code = match.charCodeAt(0);
return '\\u' + (char_code < 4096 ? '0' : '') + char_code;
},
// delegate to native `JSON.stringify` if available
stringify = typeof JSON !== 'undefined' && JSON.stringify;
// return actual polyfill
// ----------------------
return function(){
var self = this; // promote compression
if(self == null) throw new TypeError('can\'t convert ' + self + ' to object');
if(stringify) return stringify(self);
return '"' + self
.replace(escp_regex, escp_callback)
.replace(ctrl_regex, ctrl_callback)
.replace(xhex_regex, xhex_callback)
.replace(uhex_regex, uhex_callback) + '"';
}
}());
// generic version - requires Function#bind
String.quote = Function.call.bind(''.quote);
}
https://stackoverflow.com/questions/2403572
复制相似问题