diff --git a/src/dasherize.ts b/src/dasherize.ts index b0699f84..f18fdc59 100644 --- a/src/dasherize.ts +++ b/src/dasherize.ts @@ -1,6 +1,13 @@ export const dasherize = (str: unknown): string => String(typeof str === 'symbol' ? str.description : str) - .replace(/([A-Z]($|[a-z]))/g, '-$1') + // Split an acronym from a following capitalized word (`URLBar` -> `URL-Bar`, + // `mySVGIcon` -> `mySVG-Icon`). + .replace(/([A-Z]+)([A-Z][a-z])/g, '$1-$2') + // Split a lowercase letter or digit from a following capital (`fooBar` -> `foo-Bar`, + // `srcURL` -> `src-URL`). Boundaries are also kept after other non-uppercase + // characters, so `CaféBarElement` keeps its `café-Bar` boundary and `Foo_BarElement` + // keeps its `Foo_-Bar` boundary (both still register after `-element` is stripped). + .replace(/([^A-Z])([A-Z])/g, '$1-$2') .replace(/--/g, '-') .replace(/^-|-$/, '') .toLowerCase() diff --git a/test/dasherize.ts b/test/dasherize.ts index 0fbf0fb1..47e78cd8 100644 --- a/test/dasherize.ts +++ b/test/dasherize.ts @@ -9,6 +9,15 @@ describe('dasherize', () => { ['autofocusWhenReady', 'autofocus-when-ready'], ['URLBar', 'url-bar'], ['ClipX', 'clip-x'], + ['UserIDListElement', 'user-id-list-element'], + ['CopyURLElement', 'copy-url-element'], + ['mySVGIcon', 'my-svg-icon'], + ['srcURL', 'src-url'], + ['data-URL', 'data-url'], + ['data-srcURL', 'data-src-url'], + // Boundaries after non-ASCII letters and underscores are preserved (see #373 review). + ['CaféBarElement', 'café-bar-element'], + ['Foo_BarElement', 'foo_-bar-element'], [Symbol('helloWorld'), 'hello-world'] ]