설명

소스코드

function AnyStringToKebabCase(str: string): string {
    str = str
        .replace(/[-_/+]/g, " ")
        .replace(/[^0-9a-zA-Z\\s]/g, " ")
        .replace(/[\\s]{2,}/g, " ")
        .replace(/\\s/g, "-")
        .replace(/[a-z][A-Z]/g, (match) => match[0] + "-" + match[1].toLowerCase())
        .replace(/^[\\W]/, "")
        .replace(/[\\W]$/, "")
        .toLowerCase()
    ;
    return str;
}

function KebabToCamel(str: string): string {
    return str.replace(/-[a-z]/g, (match) => match[1].toUpperCase());
}

function CamelToPascal(str: string): string {
    return str[0].toUpperCase() + str.substring(1);
}

function KebabToPascal(str: string): string {
    return CamelToPascal(KebabToCamel(str));
}

// Title Name 꼴로 변환
function KebabToTitle(str: string): string {
    return str[0].toUpperCase() + 
        str.substring(1).replace(/-[a-z]/g, (match) => " " + match[1].toUpperCase());
}

테스트

function t(...args: string[]) {
    args.map((v) => {
        const kebab = AnyStringToKebabCase(v);
        const camel = KebabToCamel(kebab);
        const pascl = CamelToPascal(camel);
        console.log(`${v.padEnd(20, " ")} -> ${kebab} / ${camel} / ${pascl}`);
    })
}
t(
    "apple cat dog",
    "APPLE CAT DOG",
    "AppleCatDog",
    "Apple    Cat     Dog",
    "apple--cat__dog",
    "apple_cat_dog",
    "Apple_Cat_Dog",
    "APPLE_CAT_DOG",
    "APPLE???CAT  + DOG",
    "apple, cat, dog",
    "APPLE, Cat,dog",
    "    Apple+Cat=dog",
    " some 잘못된 Case 문자 ㅇㅁㄴㅇㅁㅈㅇ",
)
apple cat dog        -> apple-cat-dog / appleCatDog / AppleCatDog
APPLE CAT DOG        -> apple-cat-dog / appleCatDog / AppleCatDog
AppleCatDog          -> apple-cat-dog / appleCatDog / AppleCatDog
Apple    Cat     Dog -> apple-cat-dog / appleCatDog / AppleCatDog
apple--cat__dog      -> apple-cat-dog / appleCatDog / AppleCatDog
apple_cat_dog        -> apple-cat-dog / appleCatDog / AppleCatDog
Apple_Cat_Dog        -> apple-cat-dog / appleCatDog / AppleCatDog
APPLE_CAT_DOG        -> apple-cat-dog / appleCatDog / AppleCatDog
APPLE???CAT  + DOG   -> apple-cat-dog / appleCatDog / AppleCatDog
apple, cat, dog      -> apple-cat-dog / appleCatDog / AppleCatDog
APPLE, Cat,dog       -> apple-cat-dog / appleCatDog / AppleCatDog
    Apple+Cat=dog    -> apple-cat-dog / appleCatDog / AppleCatDog
 some 잘못된 Case 문자 ㅇㅁㄴㅇㅁㅈㅇ -> some-case / someCase / SomeCase