To Kebab Case

Converts a string to kebab casing.

Contributed by @itsbrunodev

javascript
function toKebabCase(str) {
  return str
    .replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g, "")
    .replace(/([a-z])([A-Z])/g, (m, a, b) => `${a}_${b.toLowerCase()}`)
    .replace(/[^A-Za-z0-9]+|_+/g, "-")
    .toLowerCase();
}
javascript
toKebabCase("hello world"); // "hello-world"

Keywords

string
casing