The simplest solution is to create a canvas in memory (i.e. one that is not added to the DOM), and then use the measureText function:
var canvas = document.createElement('canvas'); var ctx = canvas.getContext("2d"); ctx.font = "11px Arial"; var width = ctx.measureText(str).width;
source share