The JavaScript blog.


programming tricks localization

Language Detection

Posted on .

My company's blog gets translated into Japanese, and when we launched
the blog I put a link to it in the site's navigation. A few weeks later
I noticed a lot of Windows computers displayed the navigation text as a
bunch of squares, which was annoying to say the least. I suppose it's
only natural that not all computers will have all languages and fonts,
but I preferred using text to an image.

JavaScript Solution

I reasoned that most people interested in reading Japanese would have
the capability to do so, which meant I needed to conditionally display
English or Japanese based on the browser's capabilities. But how do you
detect whether or not the fonts display properly?

After researching the problem I found it's possible to detect font sizes
using half and full width katakana. When typing Japanese you can usually
select half or full width katakana: ア vs. ア. If a browser can't display
these properly, they'll be the same invalid character and therefore the
same size.

I wrote a function like this:

function japaneseFontsAvailable() {
  var halfWidth = document.createElement('span');
  var fullWidth = document.createElement('span');

  document.body.insertBefore(halfWidth, document.body.firstChild);
  document.body.insertBefore(fullWidth, document.body.firstChild);
  var havejapanesefont = halfWidth.offsetWidth != fullWidth.offsetWidth;


  return havejapanesefont;

I can't remember where I originally discovered this concept, but there's
a stackoverflow thread on the subject: Is it possible to detect East
Asian language

Have you written any similar localization hacks?


programming tricks

Express Function

Posted on .

In express yourself: rapid function
Angus Croll discusses a function that uses apply and
eval to generate functions from concise string definitions:

Function.prototype.express = function(expr) {
    var __method = this;
    return function() {
        var r = __method.apply(this, arguments);
        return eval(expr);

String.prototype.indexAfter = String.prototype.indexOf.express('r + 1');

It's a little bit like the string lambda functions in the
functional-javascript library.

Tricks like this demonstrate JavaScript's functional legacy. And, if the
eval seems a bit cheap to you, try combining the technique
with the author's previous article, Compose: functions as building

If you've been following our framework series, you've probably noticed
that jQuery, Prototype, Underscore and other libraries all define simple
functional methods early in the framework for internal use. JavaScript
1.8 makes even more techniques possible, like simplified array

Number.prototype.__iterator__ = function(){ for (let i = 0; i < this; i++) yield i }
var s = [2 * i for (i in 100) if (i * i > 3)]

And expression closures:

// JavaScript 1.7
function(x) { return x * x; }

// JavaScript 1.8
function(x) x * x