[英]XPath attribute quoting in JavaScript
I am trying to build a function that will properly quote/escape an attribute in XPath. 我正在尝试构建一个将正确引用/转义XPath中的属性的函数。 I have seen solutions posted in C# here and here , but my implementation in JavaScript results in an error "This expression is not a legal expression"
我在这里和这里都看到了用C#发布的解决方案,但是我在JavaScript中的实现导致错误“此表达式不是合法表达式”
Here is my function: 这是我的功能:
function parseXPathAttribute(original){
let result = null;
/* If there are no double quotes, wrap in double quotes */
if(original.indexOf("\"")<0){
result = "\""+original+"\"";
}else{
/* If there are no single quotes, wrap in single quotes */
if(original.indexOf("'")<0){
result = "'"+original+"'";
}else{ /*Otherwise, we must use concat() */
result = original.split("\"")
for (let x = 0;x<result.length;x++){
result[x] = result[x].replace(/"/g,"\\\"");
if (x>0){
result[x] = "\\\""+result[x];
}
result[x] = "\""+result[x]+"\"";
}
result = result.join();
result = "concat("+result+")";
}
}
return result;
}
Sample failing input: 样本失败的输入:
"'hi'"
“‘喜’”
Sample failing output: 样本失败的输出:
concat("","\\"'hi'","\\"")]
的concat( “”, “\\” 'HI' “ ”\\“”)]
I don't understand why it is an illegal expression (given that the double quotes are escaped), so I don't know how to fix the function. 我不明白为什么它是一个非法表达式(考虑到双引号已被转义),所以我不知道如何修复该函数。
\\
is not an escape character in XPath string literals. \\
不是XPath字符串文字中的转义字符。 (If it was, you could just backslash-escape one of the quotes, and never have to worry about concat
!) "\\"
is a complete string in itself, which is then followed by 'hi...
, which doesn't make sense. (如果是这样,您可以反斜杠转义其中的一个引号,而不必担心
concat
!) "\\"
本身就是一个完整的字符串,然后跟着'hi...
,该字符串不会说得通。
So there should be no backslashes in your output, it should look something like: 因此,输出中应该没有反斜杠,它应该类似于:
concat('"', "'hi'", '"')
I suggest: 我建议:
function xpathStringLiteral(s) {
if (s.indexOf('"')===-1)
return '"'+s+'"';
if (s.indexOf("'")===-1)
return "'"+s+"'";
return 'concat("'+s.replace(/"/g, '",\'"\',"')+'")';
}
It's not quite as efficient as it might be (it'll include leading/trailing empty string segments if the first/last character is a double-quote), but that's unlikely to matter. 它的效率不尽如人意(如果第一个/最后一个字符是双引号,它将包括前导/后缀空字符串段),但这不太可能。
(Do you really mean let
in the above? This is a non-standard Mozilla-only langauge feature; one would typically use var
.) (您的意思真的是
let
进入上面吗?这是一种非标准的Mozilla专用语言功能,通常会使用var
。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.