Reputation:
Why is Javascript adding a slash between the parenthesis and quote, when I'm trying to copy it. I want it removed when doing paste ctrl-v.
Console Javascript F12 in Chrome
var testData = 'By.XPath("//test")'
var resultArray = [];
resultArray.push(testData)
console.log(resultArray);
copy(resultArray);
Ctrl-V in Paste New Data, It has a slash between parenthesis and "
"By.XPath(\"//test\")"
Upvotes: 0
Views: 316
Reputation: 198324
You have a string that contains double quotes, inside an array:
[ 'By.XPath("//test")' ]
Since you're using single quotes around double quotes, there is no issue. But if you used double quotes (which are functionally equivalent in JavaScript to single quotes), like this: "By.XPath("//test")"
, you would get a syntax error, because JavaScript would think you had two strings, "By.XPath"
and ")"
, with some garbage in-between (//test
). Removing special significance of a character is called "escaping", and is done in JavaScript using the backslash (not slash) character (\
). Thus, to put a double quote inside a double-quoted string, you need to write "By.XPath(\"//test\")"
, where \"
tells JavaScript that this "
is not end of the string, but just a simple quote character.
Now, if you used copy(testData)
, you would get the exact string inside your clipboard: By.XPath("//test")
. However, you copied an array that contains this string; this stringifies the array. When an array is turned into a string, you get brackets around comma-separated list of elements, and if an element is a string, it is double-quoted. So while you got around the need of escaping by using single quotes, JavaScript refuses to choose and always uses double quotes, and then has to use the double quotes to make sure the result is not garbage ("By.XPath("//test")"
).
Upvotes: 1