Entries filed under JavaScript

Better “max-width” workaround for IE 6

IE 6 famously lacks support for CSS 2.1′s max-width and max-height properties. Most solutions involve an IE 6-exclusive expression(…) with an inline conditional:

max-width: 100px;
width: expression(this.clientWidth > 102 ? "100px" : "auto");

Despite the apparent success of this technique, I’ve still found the inline conditional to be intermittently problematic. A slightly different take on the same solution has worked better for me:

max-width: 100px;
width: expression(Math.min(this.clientWidth, 100) + "px");

Shorter, and IMO, marginally more elegant… if any IE hack could bear that label.

Mimic Positive Lookbehind in Javascript

JavaScript’s regular expression engine, while useful, lacks a few less frequently-used constructs.

I recently needed to remove all single whitespace characters (\s) immediately following semicolons (;) in a given block of text.  A simple way to accomplish this uses the positive lookbehind construct – that is, to match certain characters (;), but not to consume them, only to assert whether a match occurred or not.

This would normally be written as:

text.replace(/(?<=;)\s/g, '');

Though JavaScript doesn’t support lookbehinds, we can use a lambda expression to mimic its zero-width assertion behaviour:

text.replace(/(\;|:)?\s/g, function(str, p1) {
	return p1 ? p1 : str;
});

I haven’t tested this workaround exhaustively, but it solved the problem that needed to be overcome.

Update

It seems I’m not the first to have tackled this.  Steve Levithan’s regex skills far exceed my own, and his blog entry on the subject offers a more comprehensive solution to the problem.