Javascript method for changing snake_case to PascalCase

Viewed 7046

I'm looking for a JS method that will turn snake_case into PascalCase while keeping slashes intact.

// examples:
post -> Post
admin_post -> AdminPost
admin_post/new -> AdminPost/New
admin_post/delete_post -> AdminPost/DeletePost

etc.

I have something that will turn snake_case into camelCase and preserve slashes, but I'm having trouble converting this for PascalCase

Here's what I've got so far:

_snakeToPascal(string){
    return string.replace(/(_\w)/g, (m) => {
      return m[1].toUpperCase();
    });
  }

Any advice is appreciated!

EDIT - Solution found

Here is what I ended up using. If you use this be mindful that I'm using this._upperFirst since I'm using it in a class. It's kinda greasy but it works.

  _snakeToPascal(string){
    return string.split('_').map((str) => {
      return this._upperFirst(
        str.split('/')
        .map(this._upperFirst)
        .join('/'));
    }).join('');
  }

  _upperFirst(string) {
    return string.slice(0, 1).toUpperCase() + string.slice(1, string.length);
  }
5 Answers

PascalCase is similar to camelCase. Just difference of first char.

const snakeToCamel = str => str.replace( /([-_]\w)/g, g => g[ 1 ].toUpperCase() );
const snakeToPascal = str => {
    let camelCase = snakeToCamel( str );
    let pascalCase = camelCase[ 0 ].toUpperCase() + camelCase.substr( 1 );
    return pascalCase;
}
console.log( snakeToPascal( "i_call_shop_session" ) );

Input : i_call_shop_session

Output : ICallShopSession

const toString = (snake_case_str) => {
    const newStr = snake_case_str.replace(/([-_][a-z])/gi, ($1) => {
        return $1.toUpperCase().replace('-', ' ').replace('_', ' ');
    });
    let changedStr =
        newStr.slice(0, 1).toUpperCase() + newStr.slice(1, newStr.length);
    return changedStr;
};
let str = 'first_name';
console.log(toString(str));
Related