Simple CSS properties parser
by davidhong
JavaScript
///
/// CSS Parser method
///
/// @param css-properties {String} Semi-colon delimitered CSS properties
/// @returns {Object} JSON-style name/value pair
///
/// @usage:
/// parse('font-weight: 700; font-size: 1em', 'font-family: Verdana, sans-serif');
///
/// This is a pretty inefficient way of parsing CSS properties. The purpose here
/// is to just parse the damn thing and have it referenced like:
/// css.fontWeight;
///
var parse = (function () {
var slice = Array.prototype.slice,
split = String.prototype.split,
trim = String.prototype.trim,
forEach = Array.prototype.forEach,
replace = String.prototype.replace,
toUpperCase = String.prototype.toUpperCase,
// String.prototype.camelCase (i.e., this == the string)
camelCase = function () {
return replace.call(this, /-([a-z])/gi, function (s, c) {
return toUpperCase.call(c);
});
};
return function () {
var styles = slice.call(arguments),
css = {};
forEach.call(styles, function (style) {
var properties = split.call(style, ';');
forEach.call(properties, function (property) {
try {
var pair = split.call(property, ':');
css[camelCase.call(trim.call(pair[0]))] = trim.call(pair[1]);
} catch (propertyError) {
console.error(propertyError);
console.error('Error parsing: "' + property + '". Please fix kk thnx bye.');
}
});
});
return css;
};
}());
console.log(parse('yukky', 'font-weight: 700; font-size: 1em', 'font-family: Verdana, sans-serif', 'hello'));