Search code examples
javascriptstringgoogle-chromequotesbookmarklet

Do single/double quotes make a difference if nothing is escaped?


As I see it, both 'mars%22%3A%22' and "mars%22%3A%22" are equivalent, as nothing is being escaped.

I have been creating a javscript bookmarklet for some time now. At one point, it stopped working when pasted as-is into a bookmark in Chrome.

I discovered a solution after much guess-and-check:
A pair of double quotes needed to be single quotes. Why?

The following line with single-quotes inside split() causes no problems in a bookmarklet:

loadDoc("/page1/" + aArray[i].href.split('mars%22%3A%22')[1].slice(0,7),i);

The line below with all double quotes will cause a bookmarklet not to run at all:

loadDoc("/page1/" + aArray[i].href.split("mars%22%3A%22")[1].slice(0,7),i);

No error is shown in the console.

Note that the double-quote version will run just fine if pasted into the javascript console directly!

What am I not understanding?


Solution

  • JavaScript does not distinguish between single and double quotes in the way that a language like Ruby does (where string interpolation and backslash escape sequences only work in a double-quoted string). Both types of quote have the same meaning in JavaScript.

    The one difference is that whichever type of quote you use, that same quote can't be used inside the string unless you escape it with a backslash or URL-encode it.

    In the case of your bookmarklet, the browser unescapes the entire javascript:... URL string before executing it. You can test this with a simple case like javascript:alert('foo%22bar') which will alert the text foo"bar.

    So your string mars%22%3A%22 is converted to mars":" before the code runs. Since this string has double-quotes in it, it can only be used inside a single-quoted string.

    BTW, is my hunch correct that you may be attempting to parse or manipulate a JSON text here? If you are, it would be better to use JSON.parse() instead of the raw string manipulation.