I am trying to build a function that will properly quote/escape an attribute in 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"
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'","\"")]
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.