論盡蛋
心で書く

Blog


String display width in given font in Javascript

Aim

To calculate the width of a given character or string.

Why

Even if you use monospace fonts, there are some characters are not in the same width (such as Chinese and Japanese).

Furthermore there is no simple way to know if a given character is double-sized or not.

How

jQuery Version

#!Javascript
String.prototype.widthInFont = function(font) {
  var f = font || '12px arial',
      o = $('<div>' + this + '</div>').css({
        'position': 'absolute',
        'float': 'left',
        'white-space': 'nowrap',
        'visibility': 'hidden',
        'font': f
      }).appendTo($('body')),
      w = o.width();

  o.remove();

  return w;
}

Performance

Reference

If you have better implementation, please let me know :)


How to write Javascript bookmarklet