Skip to content

Instantly share code, notes, and snippets.

@cyjake
Last active December 10, 2015 20:49
Show Gist options
  • Save cyjake/4490971 to your computer and use it in GitHub Desktop.
Save cyjake/4490971 to your computer and use it in GitHub Desktop.
A CSS Parser written in JavaScript as a SeaJS module. Parses css text into objects.
// Usage:
//
// seajs.use('style_parser', function(parser) {
// var console.log(parser.parse('body { padding: 0; margin: 0 }'))
// })
//
// will output:
// {
// "body": {
// "padding": 0,
// "margin": 0
// }
// }
//
// The statements part should be in arrays to make sure the original order is kept.
// But for me in objects is enough.
// @author: http://cyj.me
define(function(require, exports, module) {
module.exports = {
parse: function(str) {
var chr = str[0]
var i = 0
var result = {}
function whitespace() {
while (/\s/.test(chr)) {
step()
}
}
function selector() {
var sel = ''
whitespace()
while ('{' !== chr) {
sel += chr
step()
}
step()
return chop(sel)
}
function block() {
var obj = {}
while ('}' !== chr) {
obj[property()] = value()
whitespace()
}
step()
return obj
}
function property() {
var prop = ''
whitespace()
while (':' !== chr) {
prop += chr
step()
}
step()
return chop(prop)
}
function value() {
var val = ''
whitespace()
while (!/[;\n]/.test(chr)) {
val += chr
step()
}
step()
return chop(val)
}
function chop(str) {
return str.replace(/\s+$/, '')
}
function step() {
return chr = str[++i]
}
// Just change this and the block() while loop
// if you prefer statements in array rather than object.
while (chr) {
result[selector()] = block()
whitespace()
}
return result
}
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment