Created
September 9, 2015 14:00
-
-
Save capaj/ad96ba41d06bf798c743 to your computer and use it in GitHub Desktop.
utility for converting a copied style from chrome dev tool to an object syntax which react.js expects
This file contains hidden or 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 camelCase(string) { | |
return string.replace(/-([a-z])/ig, function(all, letter) { | |
return letter.toUpperCase(); | |
}); | |
} | |
function cssToObj(css) { | |
var res = {}; | |
// split css by line | |
var css_rows = s.split('\n'); | |
// filter out empty elements and strip ';' | |
css_rows = css_rows.filter(function(x) { | |
return x !== '' | |
}).map(function(x) { | |
return x.trim().replace(';', '') | |
}); | |
for (elem in css_rows) { | |
var elem_parts = css_rows[elem].split(':'); | |
var property_name = camelCase(elem_parts[0]); | |
var property_value = elem_parts[1].trim(); | |
if (property_value.indexOf('px') !== -1) { | |
property_value = parseInt(property_value); | |
} | |
res[property_name] = property_value; | |
} | |
var filteredQuotes = JSON.stringify(res).split('{"').join('{').split(',"').join(', ').split('":').join(':') | |
return filteredQuotes; | |
} | |
var s = 'display: block;\n'; | |
s += 'width: 20px;\n'; | |
s += 'height: 20px;\n'; | |
s += 'background-color: rgb(204, 204, 204);'; | |
console.log(cssToObj(s)); // === {display:"block", width:20, height:20, backgroundColor:"rgb(204, 204, 204)"} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment