AniUI Academy

camelCase CSS property to kebab-case

easyDOM & Utilities+150 XPPractice

React style objects use camelCase, real CSS uses kebab-case, and any code that writes a stylesheet or a cssText string has to convert between them. The vendor prefixes are where naive implementations break.

Implement toKebabCase(prop). The base rule: replace every uppercase letter with a - followed by its lowercase form, so backgroundColor becomes background-color.

Two special cases. A property whose first character is uppercase is a vendor-prefixed property, so the base rule naturally produces a leading dash: WebkitLineClamp becomes -webkit-line-clamp. A property beginning with the lowercase letters ms followed by an uppercase letter is the Microsoft prefix and also needs a leading dash added, so msGridRow becomes -ms-grid-row. A custom property beginning with -- is returned exactly as given, and a name with no uppercase letters is returned unchanged.

Arguments

propstring
A camelCase CSS property name as it appears in a React style object. Vendor prefixes and --custom properties are handled too.

Returns

string — The kebab-case form of prop, with the correct leading dash for a vendor prefix.

Examples

toKebabCase("backgroundColor");
// => "background-color"

The base camelCase-to-kebab rule.

toKebabCase("WebkitLineClamp");
// => "-webkit-line-clamp"

A property starting with uppercase is a vendor prefix and keeps the leading dash.

toKebabCase("msGridRow");
// => "-ms-grid-row"

The Microsoft ms prefix is lowercase but still needs a leading dash.

toKebabCase("--brand-color");
// => "--brand-color"

Custom properties pass through untouched.

What it has to do

  • Insert a - before every uppercase letter and lowercase it.
  • Produce a leading - for properties starting with an uppercase letter, such as WebkitTransform.
  • Add a leading - for the ms prefix, so msGridRow becomes -ms-grid-row.
  • Return custom properties starting with -- untouched.
  • Return a name that is already lowercase unchanged.

Notes

  • The ms prefix is the odd one out because Microsoft chose a lowercase prefix in CSS (-ms-*) while every other vendor used an uppercase start, so React's style-object convention matches it with lowercase ms plus uppercase next letter.
  • This decision only looks at the original name — not at the transformed string — because -webkit-line-clamp and -ms-grid-row would otherwise be hard to distinguish from a stray mistake.

Stuck? The javascript course covers everything this challenge needs.

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

Discussion

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

No comments yet. Be the first to say something.