Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Parse html style string for a react component
/**
* @function parseStyles
* Parses a string of inline styles into a javascript object with casing for react
*
* @param {string} styles
* @returns {Object}
*/
const parseStyles = styles => styles
.split(';')
.filter(style => style.split(':')[0] && style.split(':')[1])
.map(style => [
style.split(':')[0].trim().replace(/-./g, c => c.substr(1).toUpperCase()),
style.split(':')[1].trim()
])
.reduce((styleObj, style) => ({
...styleObj,
[style[0]]: style[1],
}), {});
@DantSu
Copy link

DantSu commented Feb 5, 2021

This code will significantly improve the performance :

const convertStylesStringToObject = stringStyles => typeof stringStyles === 'string' ? stringStyles
    .split(';')
    .reduce((acc, style) => {
      const colonPosition = style.indexOf(':')

      if (colonPosition === -1) {
        return acc
      }

      const
        camelCaseProperty = style
          .substr(0, colonPosition)
          .trim()
          .replace(/^-ms-/, 'ms-')
          .replace(/-./g, c => c.substr(1).toUpperCase()),
        value = style.substr(colonPosition + 1).trim()
      
      return value ? {...acc, [camelCaseProperty]: value} : acc
    }, {}) : {}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment