Skip to content

Instantly share code, notes, and snippets.

@Demeter
Forked from gka/textWidth.js
Created February 3, 2014 17:11
Show Gist options
  • Save Demeter/8787968 to your computer and use it in GitHub Desktop.
Save Demeter/8787968 to your computer and use it in GitHub Desktop.
Approximating the width of a string in JavaScript
var textWidth = (function() {
function charW(w, c) {
if (c == 'W' || c == 'M') w += 15;
else if (c == 'w' || c == 'm') w += 12;
else if (c == 'I' || c == 'i' || c == 'l' || c == 't' || c == 'f') w += 4;
else if (c == 'r') w += 8;
else if (c == c.toUpperCase()) w += 12;
else w += 10;
return w;
}
return function(s) {
return _.reduce(s.split(''), charW, 0);
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment