代码之家  ›  专栏  ›  技术社区  ›  pc1oad1etter

JavaScript中的XPath属性引号

  •  0
  • pc1oad1etter  · 技术社区  · 16 年前

    here 和 here

    我的职责是:

    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;
            }
    

    “嗨”

    失败输出示例:

    我不明白为什么它是一个非法的表达式(假设双引号被转义),所以我不知道如何修复这个函数。

    1 回复  |  直到 9 年前
        1
  •  3
  •   bobince    16 年前

    \ 不是XPath字符串文本中的转义字符(如果是的话,你可以用反斜杠转义其中一个引号,而不用担心 concat !) "\" 'hi...

    所以输出中不应该有反斜杠,它应该看起来像:

    concat('"', "'hi'", '"')
    

    我建议:

    function xpathStringLiteral(s) {
        if (s.indexOf('"')===-1)
            return '"'+s+'"';
        if (s.indexOf("'")===-1)
            return "'"+s+"'";
        return 'concat("'+s.replace(/"/g, '",\'"\',"')+'")';
    }
    

    它的效率不如它可能的高(如果第一个/最后一个字符是双引号,那么它将包括前导/尾随的空字符串段),但这不太可能有什么关系。

    (你真的是说 let 在上面?这是一个非标准的Mozilla专用语言特性;人们通常会使用 var .)