Skip to content

toKebab does not work everywhere #14

@SiddharthShyniben

Description

@SiddharthShyniben

The toKebab function does not work in every case. Here are some examples:

function toKebab (string) {
  return string
    .split('')
    .map((letter, index) => {
      if (/[A-Z]/.test(letter)) {
        return ` ${letter.toLowerCase()}`
      }
      return letter
    })
    .join('')
    .trim()
    .replace(/[_\s]+/g, '-')
}

let samples = [
  "ThereIsWay_too  MuchCGIInFilms These-days",
  "UnicodeCanBeCAPITALISEDTooYouKnow",
  "CAPITALLetters at the StartOfAString_work_too",
  "As_they_DoAtTheEND",
  "BitteWerfenSie-dieFußballeInDenMüll",
  "IchHabeUberGesagtNichtÜber",
  "2BeOrNot2Be",
  "ICannotBelieveThe100GotRenewed. It-isSOOOOOOBad"
];

samples.forEach(sample => console.log(toKebab(sample)))
  1. ThereIsWay_too MuchCGIInFilms These-days becomes there-is-way-too-much-c-g-i-in-films-these-days
  2. IchHabeUberGesagtNichtÜber becomes ich-habe-uber-gesagt-nichtÜber
  3. ICannotBelieveThe100GotRenewed. It-isSOOOOOOBad becomes i-cannot-believe-the100-got-renewed.-it-is-s-o-o-o-o-o-o-bad

Why don't you try this:

// From https://stackoverflow.com/a/62527131/15511745
function toKebab(string) {
    return string.replace(/([^[\p{L}\d]+|(?<=[\p{Ll}\d])(?=\p{Lu})|(?<=\p{Lu})(?=\p{Lu}[\p{Ll}\d])|(?<=[\p{L}\d])(?=\p{Lu}[\p{Ll}\d]))/gu, '-'
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions