I need to parse the CSS font shorthand format into the separate components (font-family, font-size, font-weight, ...). This shorthand format looks pretty complicated. Here are two examples:
10px sans-serif
bold italic small-caps 1em/1.5em verdana,sans-serif
Before I start writing a parser for it, is there an already existing parser out there I could use (Preferably written in JavaScript)?
The font CSS shorthand property sets all the different properties of an element's font. Alternatively, it sets an element's font to a system font.
5.5 CSS font shorthand The font property regroups (in this particular order): font-style. font-variant. font-weight.
The CSS Font Property The font property is a shorthand property for: font-style. font-variant.
Here's a "temporary DOM element and using jquery's css() function" solution:
http://jsfiddle.net/thirtydot/tpSsE/2/
var $test = $('<span />');
$test.css('font', 'bold italic small-caps 1em/1.5em verdana,sans-serif');
alert($test.css('fontWeight'));
alert($test.css('fontStyle'));
alert($test.css('fontVariant'));
alert($test.css('fontSize'));
alert($test.css('lineHeight'));
alert($test.css('fontFamily'));
Pure free-range Javascript version:
var parsedStyleForCSS = function(cssString){
var el = document.createElement("span");
el.setAttribute("style", cssString);
return el.style; // CSSStyleDeclaration object
};
var parsedStyle = parsedStyleForCSS("font: bold italic small-caps 1em/1.5em verdana,sans-serif");
console.log(parsedStyle["fontWeight"]); // bold
console.log(parsedStyle["fontStyle"]); // italic
console.log(parsedStyle["fontVariant"]); // small-caps
console.log(parsedStyle["fontSize"]); // 1em
console.log(parsedStyle["lineHeight"]); // 1.5em
console.log(parsedStyle["fontFamily"]); // verdana, sans-serif
If you're looking to do something similar with complete stylesheets, see this answer: Parsing CSS in JavaScript / jQuery
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With