JavaScript 中转义引号的函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15877778/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Function to escape quotes in JavaScript
提问by Mantas
to start off, I don't do much JavaScript and am a complete newbie at it, now that's out of the way.. I've got a slight problem I'm trying to escape quotes from users inputs in my search app:
首先,我不会做太多 JavaScript 并且是一个完全的新手,现在已经不在了。
function getQString()
{
var query_str = 'q=' + $('input[name=q]').val().trim();
return query_str;
}
This is done as a method within a gsp file, is there something equivalent to .escape() in JavaScript?
这是作为 gsp 文件中的一个方法完成的,是否有与 JavaScript 中的 .escape() 等效的东西?
This query is later sent to elastic search and gives me hell due to the quotes especially input like a"b..
这个查询后来被发送到弹性搜索,并且由于引号特别是像 a"b..
I'm using ES 0.20.6
我正在使用 ES 0.20.6
回答by
query_str = query_str.replace(/"/g, '\\"');
..will result in; "
to \"
..将导致; "
到\"
OR
或者
query_str = query_str.replace(/"/g, '\\\"');
..will result in; "
to \\"
, which will make a printed quotation still be escaped to \"
.
..将导致; "
to \\"
,这将使打印的报价仍然转义为\"
.
This code;
这段代码;
var test = 'asdasd " asd a "';
console.log(test.replace(/"/g, '\\"'));
console.log(test.replace(/"/g, '\\\"'));
..outputs;
..输出;
asdasd \" asd a \"
asdasd \" asd a \"
You might adjust the replacement based on how your final interpreter reads the string and prints it out.
您可以根据最终解释器读取字符串并将其打印出来的方式来调整替换。