camelCase CSS property to kebab-case
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
styleobject. Vendor prefixes and--customproperties 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 asWebkitTransform. - Add a leading
-for themsprefix, somsGridRowbecomes-ms-grid-row. - Return custom properties starting with
--untouched. - Return a name that is already lowercase unchanged.
Notes
- The
msprefix 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 lowercasemsplus uppercase next letter. - This decision only looks at the original name — not at the transformed string — because
-webkit-line-clampand-ms-grid-rowwould otherwise be hard to distinguish from a stray mistake.
Stuck? The javascript course covers everything this challenge needs.
- 1.converts a normal camelCase property
- 2.handles a leading uppercase vendor prefix
- 3.adds the leading dash for the ms prefix
- 4.leaves a lowercase property unchanged
- 5.leaves a custom property untouched
These assertions run in your browser the moment you hit Run. Pass all of them to claim the XP.
Discussion
Sign in to postNo comments yet. Be the first to say something.