Skip to content

Instantly share code, notes, and snippets.

@nblackburn
Last active December 15, 2023 03:19
Show Gist options
  • Star 84 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save nblackburn/875e6ff75bc8ce171c758bf75f304707 to your computer and use it in GitHub Desktop.
Save nblackburn/875e6ff75bc8ce171c758bf75f304707 to your computer and use it in GitHub Desktop.
Convert a string from camel case to kebab case.
module.exports = (string) => {
return string.replace(/([a-z0-9]|(?=[A-Z]))([A-Z])/g, '$1-$2').toLowerCase();
};
@ibockowsky
Copy link

Here is another one:

module.exports = (string) => {
    return string.replace(/\B(?:([A-Z])(?=[a-z]))|(?:(?<=[a-z0-9])([A-Z]))/g, '-$1$2').toLowerCase();
};

It supports the following conversions (either camel or pascal case to kebab case):

fooBar                              ->  foo-bar
FooBar                              ->  foo-bar
AFooBar                             ->  a-foo-bar
AFooBarACRONYM                      ->  a-foo-bar-acronym
ACRONYMFooBar                       ->  acronym-foo-bar
FooACRONYMBar                       ->  foo-acronym-bar
ACRONYMFooACRONYMBarACRONYM         ->  acronym-foo-acronym-bar-acronym
ACRONYM1Foo1ACRONYM2Bar1ACRONYM3    ->  acronym1-foo1-acronym2-bar1-acronym3

unluckily it's not support in Safari :(

@bradgreens
Copy link

unluckily it's not support in Safari :(

I was curious why.... so here is why.

https://stackoverflow.com/a/51568859

Looks like Safari doesn't support lookbehind yet (that is, your (?<=/)).

@rawlinc
Copy link

rawlinc commented May 6, 2021

@bradgreens @ibockowsky Yeah, I should have reported back when I found out about lack of support with lookbehind assertions in Safari. I ran into that during browser testing too.

I've updated my original comment with what I used to get around Safari's lack of lookbehind assertion support.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment