Limiting the contents of a string via RegEx

Often, you will need to prevent users from entering data that doesn’t conform to a specific pattern. For example, you may want to allow users to enter only numbers or only valid email addresses. To this end, I’ve written a little utility function that returns the “standardised” version of a string, according to the regex you supply.

	limitContent: function(allowedRegex) {
		return $splat(this.match(allowedRegex)).join('');

Basically, the function takes the result of evaluating the regular expression on the string, converts it into an array if it isn’t one, and then joins the array’s elements together with an empty string.


console.log("12345".limitContent(/.{4}/)); // Only allow four characters
console.log("".limitContent(/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}/)); // Only allow email addresses

Google Wave & iPhone

I just tried out Google Wave on the iPhone. Interestingly, despite an initial “your browser is not supported” message, the actual system sports a rather snazzy app-like interface on the iPhone.

I’ll be interested to see what kind of support Wave will ‘officially’ have on mobile platforms, and perhaps even more interested in what ‘unofficial’ support there’ll be.

CSS Columns

In this post, I will walk through the new columns specification that arrived in CSS 3. I will show you the current implementation state of columns in the four major rendering engines: Gecko (Firefox), Webkit (Safari & Chrome), Trident (Internet Explorer), and Presto (Opera).

Before we get on to platform-specific issues and workarounds, though, we’ll look at the various CSS properties available for working with columns.

For more in-depth information on columns, you should check out the W3C working draft and Mozilla’s MDC page on columns. The Webkit blog also has an article, but it’s not particularly informative.


I will add more to this entry as I discover more about columns — the goal is to make it an easy-to-understand reference.

Browser capabilities

Property Gecko Webkit Trident Presto
column-count -moz-column-count -webkit-column-count
column-width -moz-column-width -webkit-column-width
columns -webkit-columns
column-gap -moz-column-gap -webkit-column-gap
column-rule-color -moz-column-rule-color -webkit-column-rule-color
column-rule-style -moz-column-rule-style -webkit-column-rule-style
column-rule-width -moz-column-rule-width -webkit-column-rule-width
column-rule -moz-column-rule column-rule

Browsers used for testing: Firefox 3.5.4 (Windows), Safari 4.0.2 (Windows), Internet Explorer 8.0.6001, Opera 10.00 (Windows)

Please let me know if this table is inaccurate, and I will update it.

Browser bugs

These are the bugs that I have encountered using CSS columns — if you know of more, please let me know, and I’ll add them to these lists.

Gecko bugs

  • Specifying an “overflow” (or “overflow-x” or “overflow-y”) property on an element with columns prevents the column rule from being rendered at all.
  • Column rules occasionally don’t render, regardless of the “overflow” property.
  • There is no way to break columns.

Webkit bugs

  • Pixel creep: Pixels from a later column can creep back to the bottom of the previous column. This can happen with plain text, but it is much more noticeable when you use a non-layout altering effect like text-shadow or box-shadow.
  • Text that overflows the column horizontally is chopped off
  • There is no way to break columns.



Value: | auto
Initial value: auto

If you don’t set the column-width property, column-count specifies the number of columns into which the content should be flowed.

If you specify column-width, column-count imposes a limit on the maximum number of columns to be rendered if you supply a numeric value.


Value: | auto
Initial value: auto

This property indicates the optimal column width — columns may be rendered narrower or wider by the UA, according to the available space.

If column-width has the value “auto”, then the width of the columns is determined by other means (for example, column-count).


Value: column-width && column-count

The columns property is a short-hand property, used to set both column-width and column-count simultaneously.


Value: | normal
Initial value: normal

Use column-gap to specify the size of the gutter that lies between columns. Most UAs will render “normal” as 1em.



When a column-rule is specified, you may use column-rule-color to set the colour for the line drawn between columns. This property is approximately equivalent to the various border-(?)-color properties.



By using column-rule-style, you may determine how the line between columns is to be rendered, if at all. Similar to border-(?)-style.


Initial value: medium

column-rule-width sets the width of the line rendered in the gutter between columns. Basically, it’s the same as the border-(?)-width properties.


Value: column-rule-width && column-rule-style & & column-rule-color

Shorthand for setting all three column-rule properties.


Value: 1 | all
Initial value: 1

By using column-span, you can allow an element to span either the entire set of columns, or none at all.

Note that you cannot set an arbitrary number of columns to span — this property essentially ‘interrupts’ the column flow and restarts it below the spanned element.


Value: auto | balance
Initial value: balance

If you have set a height for your columnified element, setting column-fill to ‘auto’ will cause the columns to be ‘filled’ in turn, rather than have the content balanced equally between them.

Apple Keyboard & Windows

At work, I recently moved to one of the slim aluminium Apple keyboards, and I love it. Linux and the keyboard play nicely together without any hassles whatsoever. So, emboldened by this success, I bought another one for use at home — with my Windows machine. The results were, well, less than dazzling.

Whilst the keyboard’s basic functions pose no problem to Windows — it is, after all, just a USB keyboard — there were some problems, especially with the Function keys. Basically, the [fn] key doesn’t seem to generate a recognisable keycode for Windows, which meant that I didn’t have access to all the spiffy multimedia controls and so on.

After much googling and installation of keyboard drivers originally distributed with Apple’s Boot Camp, I eventually stumbled across a great little utility by Petr Laštovička, which allows a fairly clean and simple remapping of keys to functions. [For the Googlers who’ve arrived here looking for a solution to the Mac Keyboard + Windows problem, it beats out Sharpkeys for me because it can handle key combos.]

So, ultimately, I have ended with a very good-looking, nice-feeling keyboard that works 99% of the way I want it to. My biggest gripe is that changing the volume now requires me to press [Command]+[Fn]+[F10/F11/F12], rather than just [Fn]+[F10/F11/F12], as I can in Linux. I’m quite happy with this keyboard — although it’s not 100%, it’s definitely much better than most similarly-priced keyboards (at $69AUD).

Quicksort an array of objects

Often, you will need to sort an array of objects in Javascript. The inbuilt sort() function can’t do this, but here is a Quicksort implementation for doing just this.


array The array to be sorted. (See below for an implementation on the Array Native itself, which makes this variable unnecessary).

key The key to sort by. Make sure every object in your array has this key.


var objs = [

// Logs [{fruit:"apple"},{fruit:"banana"},{fruit:"cherry"}] to the console

The code

sortObjects: function(array, key) {
	for (var i = 0; i < array.length; i++) {
		var currVal = array&#91;i&#93;&#91;key&#93;;
		var currElem = array&#91;i&#93;;
		var j = i - 1;
		while ((j >= 0) && (array[j][key] > currVal)) {
			array[j + 1] = array[j];
		array[j + 1] = currElem;

Implemented on the Array native:

	sortObjects: function(key) {
		for (var i = 0; i < this.length; i++) {
			var currVal = this&#91;i&#93;&#91;key&#93;;
			var currElem = this&#91;i&#93;;
			var j = i - 1;
			while ((j >= 0) && (this[j][key] > currVal)) {
				this[j + 1] = this[j];
			this[j + 1] = currElem;

Javascript string ellipsising

Putting ellipses into strings that are too long has been around for a very long time. Unfortunately, Javascript doesn’t offer a native method of doing this, so below is a little function that’ll do it for you.

This function returns a copy of the string it’s called on, ellipsised, and takes three parameters:

toLength (required) The number of characters to truncate the string to (or 0 to disable ellipsising)

where (optional, default ‘end’) A string representing where the ellipsis should be placed — ‘front’, ‘middle’, or ‘end’

ellipsis (option, default ‘\u2026’) A string to be used as the ellipsis.


// Our clichéd string
var s = 'Jackdaws love my great big sphinx of quartz';

// Alerts "Jackdaws l…"

alert(s.ellipsise(10, 'front'));
// Alerts "… of quartz"

alert(s.ellipsise(10, 'middle', 'pony'));
// Alerts "Jackdponyuartz"

The code

ellipsise: function(toLength, where, ellipsis) { // Where is one of [‘front’,’middle’,’end’] — default is ‘end’
if (toLength < 1) return this; ellipsis = ellipsis || '\u2026'; if (this.length < toLength) return this; switch (where) { case 'front': return ellipsis + this.substr(this.length - toLength); break; case 'middle': return this.substr(0, toLength / 2) + ellipsis + this.substr(this.length - toLength / 2) break; case 'end': default: return this.substr(0, toLength) + ellipsis; break; } } });[/sourcecode] If you're not using MooTools, you can use this variant instead: [sourcecode language='javascript']String.prototype.ellipsise = function(toLength, where, ellipsis) { // Where is one of ['front','middle','end'] -- default is 'end' if (toLength < 1) return this; ellipsis = ellipsis || '\u2026'; if (this.length < toLength) return this; switch (where) { case 'front': return ellipsis + this.substr(this.length - toLength); break; case 'middle': return this.substr(0, toLength / 2) + ellipsis + this.substr(this.length - toLength / 2) break; case 'end': default: return this.substr(0, toLength) + ellipsis; break; } }[/sourcecode]

Avoid Javascript’s ‘with’ keyword

Javascript is a fantastic language — in fact, it’s become the language that I do most of my programming in nowadays. It’s flexible, fast, and powerful. Unfortunately, though, it suffers from a few flaws, which, although not critical, can be frustrating. One of the potentially most confusing features is the with keyword, which promises a lot, but can really just make life difficult.

The with keyword might appear to be harmless enough: it allows you to avoid typing long references; instead of = 'In the jungle';

we can type

with ( {
  lyric = 'In the jungle';

But what happens if we happen to have a variable in scope named lyric? In the example below, which lyric should be modified?

var lyric = 'In the jungle';
with ( {
  lyric = 'The mighty jungle';

The simplest way to deal with this issue is to use a variable:

var a =;
a.lyric = 'The mighty jungle';

Now there is no ambiguity.

Based on a post by Douglas Crockford at the YUI Blog.

Internet Explorer DOMDocument & XPath

I discovered a couple of interesting things about Internet Explorer’s MSXML2.DOMDocument object. It turns out that there are essentially two “production-quality” versions of it available: 3.0 and 6.0. Version 6.0 is much the better version, but it’s quite new, and not available on all systems. This means that in IE7 and IE8, instantiating a new MSXML2.DOMDocument object gives you version 3.0.

Now most of the time, this isn’t a problem. Today, though, I was constructing an XPath expression that used the substring() function; something like this:

//Element[substring(Child, 1, 3)='abc']

This will pull all Elements with a Child element whose value’s first three characters are “abc”. Not particularly complex. It turns out, though, that version 3.0 or the DOMDocument doesn’t actually use XPath as its default language: it uses a bastardised version of XPath called “XSLPatterns”, which just so happens to not support the substring() function at all.

So how do we deal with this situation? One way is to always instantiate version 6.0 of the DOMDocument:

xd = new ActiveXObject('msxml2.DOMDocument.6.0')

The problem with this approach is that, like I mentioned earlier, you can’t always be guaranteed that your users will have version 6.0 installed (even though it’s a free download). The safer way to deal with this problem is to switch the expression language to XPath in your 3.0 object:

xd = new ActiveXObject('msxml2.DOMDocument');
xd.setProperty("SelectionLanguage", "XPath");

The advantage of this approach is that you’re not specifying a version, so when MS eventually changes the default to 7.0 (or whatever), your code will work without a problem.

For more information on this, check out  this blog post from Microsoft’s XML team, which goes into a little bit more detail.

Javascript-generated tables and rowspan

At work, I’ve recently been putting together a nice little calendar-like utility using Javascript. Basically, it has to generate a table consisting of cells which may span multiple rows. Surely the solution is simple enough: just set the rowspan on each td as we create it. Unfortunately, that doesn’t work, at least not in Firefox.

It appears that in Firefox, if you create a td and set its rowspan to some value when there are no rows for it to expand into, the attribute will be completely ignored, even if you add rows afterwards! Needless to say, this is very annoying. The solution? Build your table backwards.

The code I have now is something like this (note that I’m developing using the Mootools framework):

var tbl = new Element('table');
var trs = [];

for (var i = 0; i < 4; i++) {
  var tr = new Element('tr');
  tr.grab(new Element('td', {
    'html': 'Cell ' + i
  if (i % 2 == 0) {
    tr.grab(new Element('td', {
      'rowspan': 2,
      'html': 'Span ' + (i / 2)

for (var i = trs.length - 1; i >= 0; i--) {
  tbl.grab(trs[i], 'top');

What does this code do? Well basically, we’re creating a table with ten rows and two columns; the cells in the right-hand column each occupy two rows. The result will be something like this:

Cell 1 Span 1
Cell 2
Cell 3 Span 2
Cell 4

Ubuntu and sudo

Ubuntu disables access to the root account by default, for reasons which have never been particularly clear to me. They deem it preferable to give users sudo access, which is all well and good, but typing a series of commands, all prefixed by ‘sudo’, can be very tedious.

Fortunately, there are a few ways around this.

The first is to use a super user shell. From a terminal or console, type:
sudo bash
This will give you a shell with full root access, and save you needlessly typing ‘sudo’. (You can, of course, use other shell flavours, like zsh or csh if you prefer.)

A similar method is to run the ‘su’ command with sudo, thusly:
sudo su
which will also give you a shell with full root access, according to root’s preferred shell.

The third method is to alter the password protecting the root account. To do this, from a terminal or console, type:
sudo passwd root
and enter a password for the root user. Now you will be able to log on to consoles (and, if you’re that way inclined, X sessions) as root.

Changing Windows’ default font

You may have noticed that Windows has a rather haphazard way of applying the fonts specified in Visual Styles. That is to say, whilst a particular visual style may attempt to enforce a particular font, Windows will often ignore this in applications and dialogs.

The problem is a registry key, which enforces font substitutions in Windows. Now, most applications specify their font as MS Shell Dlg or MS Shell Dlg 2. By default, these two fonts are replaced by Microsoft Sans Serif and Tahoma, respectively. To achieve a more uniform feel across your system, all that you need to do is edit these substitutions.

To do this, run ‘regedit’ from your Start menu. Then navigate to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\FontSubstitutes. You should see a list of key/value pairs on the right. Simply double-click on the entries for MS Shell Dlg and replace their contents with the font of your choice — make sure, however, that you spell it exactly right.

That’s it! The change will be in effect once you restart. Bear in mind that this is a change made to the entire Windows installation, not just your user settings.