AniUI Academy

Parse inline CSS into a style object

mediumDOM & Utilities+250 XPPractice

Pasted markup, a WYSIWYG editor's output, or a legacy template all hand you inline CSS as text. To hand it to React you need it as a camelCased object, and to merge it with your own styles you need the cascade rules right.

Implement cssTextToObject(cssText). Split the text on ; and trim each declaration, skipping empty ones. Split each declaration on its **first** : so a value containing a colon survives, then trim both sides. Skip any declaration with no :, an empty property name, or an empty value.

Convert the property name to camelCase by uppercasing the character after each - and removing the -. A name starting with -- is a custom property and is used exactly as written. Otherwise a single leading - is dropped first, so -webkit-transform becomes webkitTransform.

Values are always kept as trimmed strings, never converted to numbers, so margin: 0 gives "0". If the same property is declared twice, the last declaration wins, as it does in CSS. An empty input returns {}.

Arguments

cssTextstring
The contents of a style="..." attribute as a string. An empty string returns {}.

Returns

Record<string, string> — A React-friendly style object with camelCase keys and trimmed string values. Custom properties keep their -- prefix.

Examples

cssTextToObject("color: red; background-color: blue");
// => { color: "red", backgroundColor: "blue" }

Kebab property names camelCase into React style keys.

cssTextToObject("background-image: url(https://a.test/x.png)");
// => { backgroundImage: "url(https://a.test/x.png)" }

Splitting on the first colon only keeps url(https://...) intact.

cssTextToObject("--brand-color: #ff0; -webkit-transform: scale(2)");
// => { "--brand-color": "#ff0", webkitTransform: "scale(2)" }

Custom properties pass through verbatim; a leading vendor dash is dropped before camelCasing.

What it has to do

  • Split declarations on ; and each declaration on its first : only.
  • Skip malformed declarations: no colon, empty name, or empty value.
  • camelCase kebab names, keep --custom properties verbatim, and drop a single leading - before camelCasing.
  • Keep every value as a trimmed string.
  • Let the last declaration of a repeated property win, and return {} for empty input.

Notes

  • Values are kept as strings because "0" and 0 mean the same thing to CSS but completely different things to a React style object — numbers would get px appended downstream.
  • This is the inverse of styleObjectToCss and makes a reasonable round-trip when the CSS was written as kebab-case; it does not try to re-create things like !important or url() shorthand.

Stuck? The javascript course covers everything this challenge needs.

Try it yourself
Loading playground...
5 tests · +250 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.