%27 = ‘ in JavaScript Strings?

Patrick kindly took the time to let me know about an issue with my Share This plugin for WordPress: apostrophes/single-quotes in post titles break things.

The thing is, the string looks fine in the source. The title:

This title's got an apostrophe

is turned into:

This+title%27s+got+an+apostrophe

just as I’d intended.

What I didn’t realize was that the browser would decode the URL string and allow the %27 to behave as a ', thus breaking the JavaScript string that was enclosed in ' marks.

I’m not sure what to make of this – the JavaScript string is perfectly valid on its face, there is no single quote in the string to backslash/escape, yet the browser’s url-decoding seems to create the problem.

A little more research shows this to only be a problem if the string is in the href attribute. If I put the string in an onclick attribute, everything is hunky-dory1.

Here is a test case.

Any web or browser developers out there that can enlighten me on this one? Perhaps this is standard documented behavior and I need to handle the string in a different manner? Perhaps it’s a known bug with a good work-around?

I eagerly await waking in the morning to your sympathetic sentiments, stinging criticism and lambasting in the comments. 😉

  1. Which looks like a suitable work-around, but I’d still like to understand how and why this works as it does. [back]