Archive for November, 2008

Splitting a long JavaScript String across multiple lines

Wednesday, November 12th, 2008

Whilst reading a comment by Mike DeBoer on Ajaxian about delimiting JavaScript strings with backslashes, I thought it’s worth mentioning it here as well, if only to remind myself.

String concatenation always creates a new string.

Thus, writing:

 
var str = "This is a long" +
  " string. That's why we want to " +
  " split it over several lines";
 

is slower & more memory intensive than writing:

 
var str = "This is a long\
 string. That's why we want to\
 split it over several lines";
 

Just be careful you don’t have trailing spaces as that will mess it up.

JavaScript cookies made easy

Tuesday, November 4th, 2008

Here is another little script that makes my life a bit easier. It consists of 3 methods that makes working with cookies very straight forward. This script is built on the shoulder of giants: PPK from Quircksmode was the man who did the hard work.

However, rather than creating 3 methods that sit in the global namespace, I wanted to use a singleton object that would only add 1 global variable. Since there is no need for private methods, the object literal pattern is appropriate.
In my opinion the names of the methods make it very straight forward to use. Good names mean less looking up, mean less mistakes, mean faster development. Your Technical Project Manager will love you for it :-)

To create/set a cookie:
cookie.set('name', 'value, 234); // last argument is number of days until expiry. If none is provided, it will get deleted when the browser is closed

To get the cookie value:
cookie.get('name');

To delete the cookie:
cookie.erase('name');

As always, you can download the latest version from my svn repository