javascriptcamelcasingpascalcasingkebab-case

How do I covert kebab-case into PascalCase?


How could I convert this to PascalCase and to camelCase?

var text = "welcome-to-a-New-day";
toPascalCase(text); // "WelcomeToANewDAY"
toCamelCase(text); // "WelcomeToANewDAY"

Solution

  • A fully ES5 compatible way to do this is, to find all the dashes that are followed by an alphanumeric character using this simple regex /-\w/g. Then just remove the dash and uppercase the character.

    The same can be done for pascal case just by also checking for the first character in the string using ^\w|-\w. The rest is the same.

    Here are a couple of examples:

    console.log(toCamelCase("welcome-to-a-New-day"));
    console.log(toPascalCase("welcome-to-a-New-day"));
    console.log(toCamelCase("bsd-asd-csd"));
    console.log(toPascalCase("bsd-asd-csd"));
    
    function toCamelCase(text) {
      return text.replace(/-\w/g, clearAndUpper);
    }
    
    function toPascalCase(text) {
      return text.replace(/(^\w|-\w)/g, clearAndUpper);
    }
    
    function clearAndUpper(text) {
      return text.replace(/-/, "").toUpperCase();
    }