HTML5, CSS3, jQuery, JSON, Responsive Design...

The JavaScript Apostrophe Bug

Michael Brown   December 13 2009 04:16:33 PM
Not actually a bug in JavaScript, but a bug that you're likely to program in JavaScript without even realising it.  This is especially true if you're dealing with Domino or any other back-end system where you have real user names.  By "real user names", I mean "Michael Brown" rather than "brownm".

Here's the scenario.  You have some JavaScript code that retrieves a user's name from somewhere, whether through a Domino function (i.e. @UserName) or from an Ajax call.  Once retrieved, you assign that user name to a JavaScript variable, like so:

var userName = $get(salaryNumber);

(I'm using the JQuery $get Ajax call here, but it doesn't really matter how you retrieve the user's name.)  

Using some DHTML we take this stored variable and write it out to your web page form for the user to click on a link, using the link's onClick event.  We end up with something like this on our web page:
<a href="#" onclick="storeValue('Joe Bloggs')">Click to select blah, blah</a>

Now, everything's fine as long the user name retrieved is "Joe Bloggs", but if the name is something like "Paddy O'Riley" you'll have this:
<a href="#" onclick="storeValue('Paddy O'Riley')>"Click to select blah, blah</a>

See the problem? The apostrophe is the same character as the single quote, which just happens to be a string terminator in JavaScript.  So, JavaScript chops the string as just "Paddy O", and the rest following that becomes garbage in JavaScript's eyes.  This may or may not stop your application dead in its tracks, but it will undoubtedly come back to bite you in the arse at some point, if you don't fix it.

We need a it of defensive coding here.  We need to write the user's name on our web page with the backslash escape character before the apostrophe, like so:

<a href="#" onclick="storeValue('Paddy O\'Riley')">Click to select blah, blah</a>

Here's a Javascript function that I'm using to get around the problem:

function formatApostopheWithEscapeChar(sourceString) {
return(replaceSubstring(sourceString, '\'', '\\\''));

There's no replaceSubstring function built into JavaScript, so I've borrowed this one from Tomas Nielsen:

function replaceSubstring(exp, str, wit) { return exp.split(str).join(wit); }

So now, when writing the value onto the web page, we'd need to the write function (e.g. innerHTML) to formatApostopheWithEscapeChar(userName) instead of just userName on its own.

1Kerry  12/13/2009 7:10:54 PM  The JavaScript Apostrophe Bug

Thats a good reminder; I have bene caught by that a few times.