Created
August 2, 2011 04:02
-
-
Save hongymagic/1119577 to your computer and use it in GitHub Desktop.
A Simple CSS Properties parser
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// | |
/// 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; | |
}; | |
}()); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
console.log(parse('yukky', 'font-weight: 700; font-size: 1em', 'font-family: Verdana, sans-serif', 'hello, world!')); | |
// Should print: | |
// { | |
// fontWeight: '700', | |
// fontSize: '1em', | |
// fontFamily: 'Verdana, sans-serif' | |
// } | |
// | |
// Should also print some errors |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment