Skip to content

Instantly share code, notes, and snippets.

@goldhand
Last active March 18, 2023 16:28
Show Gist options
  • Save goldhand/70de06a3bdbdb51565878ad1ee37e92b to your computer and use it in GitHub Desktop.
Save goldhand/70de06a3bdbdb51565878ad1ee37e92b to your computer and use it in GitHub Desktop.
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],
}), {});
@KorbinianMoser
Copy link

A minor improvement for line 13, to make background-images with "http://" survive:
style.split(':').slice(1).join(':').trim()

@JoshuaSoileau
Copy link

👍 this is helpful, thank you

@SandalovAV
Copy link

In https://reactjs.org/docs/dom-elements.html#style written:
...Vendor prefixes other than ms should begin with a capital letter. ...
So:
style.split(':')[0].trim().replace(/-./g, c => c.substr(1).toUpperCase())
must be replaced with:
style.split(':')[0].trim().replace(/^-ms-/, 'ms-').replace(/-./g, c => c.substr(1).toUpperCase())

@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