Created
August 5, 2015 11:58
-
-
Save MoOx/2808f7473dbc04b44f0f to your computer and use it in GitHub Desktop.
Transform CSS declaration block into JavaScript Object
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
function toSpaceCase (string) { | |
return string.replace(/[\W_]+(.|$)/g, function (matches, match) { | |
return match ? ' ' + match : ''; | |
}); | |
} | |
function toCamelCase(string) { | |
string = toSpaceCase(string).replace(/\s(\w)/g, function (matches, letter) { | |
return letter.toUpperCase(); | |
}); | |
return string.charAt(0).toLowerCase() + string.slice(1) | |
} | |
function cssToObject(string) { | |
return ( | |
string | |
.split(";") | |
.reduce((acc, decl) => { | |
decl = decl.split(": ") | |
if (decl.length > 1) { | |
acc[toCamelCase(decl[0])] = decl[1] | |
// replace 0px by 0 | |
.replace(/\b0px\b/, "0") | |
} | |
return acc | |
}, {}) | |
) | |
} | |
function CSSDeclarationBlockToJSObject(string) { | |
return JSON.stringify(cssToObject(string), null, 2) | |
.replace(/ "([a-zA-Z]+)"/g, " $1") | |
.replace("\n}", ",\n}") | |
} |
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(CSSDeclarationBlockToJSObject(` | |
display: block; | |
padding-left: 2rem; | |
margin: 3rem 0px 1rem; | |
font-weight: 700; | |
font-size: 1.125rem; | |
color: #4A4A4A; | |
`)) | |
/* | |
{ | |
display: "block", | |
paddingLeft: "2rem", | |
margin: "3rem 0 1rem", | |
fontWeight: "700", | |
fontSize: "1.125rem", | |
color: "#4A4A4A", | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment