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],
}), {});
@danakt
Copy link

danakt commented Nov 8, 2018

parseStyles('background-image: url(\'https://example.com/image.png\')')

returns:

{
  "backgroundImage":"url('https"
}

@KorbinianMoser
Copy link

KorbinianMoser commented Mar 19, 2019

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

@JoshuaSoileau
Copy link

JoshuaSoileau commented Jul 12, 2019

👍 this is helpful, thank you

@SandalovAV
Copy link

SandalovAV commented Jul 4, 2020

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