Last active
July 9, 2016 18:10
-
-
Save danbrianwhite/9ce911d7c2a0f81a15ed to your computer and use it in GitHub Desktop.
CSS style string to React JS 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
var camelCaseCSS = function(property) { | |
property = property.replace(/^-ms-/gi, 'ms-'); | |
return property.replace(/-\w/g, function(match){ | |
return match.charAt(1).toUpperCase(); | |
}); | |
}; | |
var cssStyleToJS = function(cssStyles) | |
{ | |
var _cssStyles = {}; | |
cssStyles = cssStyles.replace(/\s/g, ''); | |
if(typeof cssStyles !== 'undefined') { | |
var styles = cssStyles.split(';'); | |
for (var i = 0; i < styles.length; i++) { | |
var style = styles[i].split(':'); | |
if (style.length === 2) { | |
_cssStyles[camelCaseCSS(style[0])] = style[1].replace(/^\s+|\s+$/, ''); | |
} | |
} | |
} | |
return _cssStyles; | |
}; | |
var jsStylesToString = function (jsStyles) { | |
var stringStyles = ''; | |
for (style in jsStyles) { | |
jsStyles[style] = jsStyles[style] === "''" ? '' : jsStyles[style]; | |
stringStyles += (style + ': \'' + jsStyles[style] + '\',\n') | |
} | |
stringStyles = stringStyles.replace(/,\n$/, ''); | |
return stringStyles; | |
}; | |
var cssStyleToJSToString = function(cssStyles) | |
{ | |
return jsStylesToString(cssStyleToJS(cssStyles)); | |
} | |
var styleSheetToString = function(cssStyleSheet){ | |
var splitStyles = cssStyleSheet.split(/\{|\}/); | |
if(splitStyles.length === 0) | |
{ | |
return cssStyleToJSToString(cssStyleSheet); | |
} | |
else if(splitStyles.length === 1) | |
{ | |
return cssStyleToJSToString(splitStyles[0]); | |
} | |
else | |
{ | |
var stylesheetString = '{\n'; | |
for(var i = 0; i < splitStyles.length; i ++) | |
{ | |
if(i%2 === 0) | |
{ | |
if(splitStyles[i].trim() !== '') | |
{ | |
if(i !== 0) | |
{ | |
stylesheetString+='\n },\n'; | |
} | |
stylesheetString+=' "'+splitStyles[i].trim().replace(/\n/g, ' ')+'": {\n' | |
} | |
} | |
else | |
{ | |
stylesheetString+=cssStyleToJSToString(splitStyles[i].trim()).replace(/^/g, ' ').replace(/\n/g, '\n '); | |
} | |
} | |
stylesheetString+='\n }\n}' | |
return stylesheetString; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment