9

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);
  }
Kieran E
  • 3,616
  • 2
  • 18
  • 41

7 Answers7

7

Here's a solution that preserves slashes and converts snake_case to PascalCase like you want.

const snakeToPascal = (string) => {
  return string.split("/")
    .map(snake => snake.split("_")
      .map(substr => substr.charAt(0)
        .toUpperCase() +
        substr.slice(1))
      .join(""))
    .join("/");
};

It first splits the input at the '/' characters to make an array of snake_case strings that need to be transformed. It then splits those strings at the '_' characters to make an array of substrings. Each substring in this array is then capitalized, and then rejoined into a single PascalCase string. The PascalCase strings are then rejoined by the '/' characters that separated them.

kamoroso94
  • 1,713
  • 1
  • 16
  • 19
6

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

M. Hamza Rajput
  • 7,810
  • 2
  • 41
  • 36
  • I'm using this version as vuejs method: `snake2pascal(str) { let camelCase = str.replace(/([-_]\w)/g, (g) => g[1].toUpperCase()); return camelCase[0].toUpperCase() + camelCase.substr(1);}` – DevonDahon Dec 01 '22 at 10:41
1

This should do the trick.

function _snake2Pascal( str ){
    str +='';
    str = str.split('_');
    for(var i=0;i<str.length;i++){ 
        str[i] = str[i].slice(0,1).toUpperCase() + str[i].slice(1,str[i].length);
    }
    return str.join('');
}

edit:

a version that passes all your test cases shown in the OP:

function snake2Pascal( str ){
    str +='';
    str = str.split('_');

    function upper( str ){
        return str.slice(0,1).toUpperCase() + str.slice(1,str.length);
    }


    for(var i=0;i<str.length;i++){
        var str2 = str[i].split('/');
        for(var j=0;j<str2.length;j++){
            str2[j] = upper(str2[j]);
        }
        str[i] = str2.join('');
    }
    return str.join('');
}
r3wt
  • 4,642
  • 2
  • 33
  • 55
1

Or something like that:

function snake2CamelCase(string) {
  return string
    .replace(
      /_(\w)/g,
      ($, $1) => $1.toUpperCase()
    )
  ;
}

function snake2PascalCase(string) {
  let s = snake2CamelCase(string);
  
  return `${s.charAt(0).toUpperCase()}${s.substr(1)}`; 
}


[
  'something_went_wrong',
  'thisIs_my_snakecase'
]
  .map(s => ({[s]: snake2PascalCase(s)}))
  .forEach((s, i) => console.log(i, s))
;
Hitmands
  • 13,491
  • 4
  • 34
  • 69
0
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));
Muhammad Dyas Yaskur
  • 6,914
  • 10
  • 48
  • 73
0
let str = "hello_foo_bar" // Your string in camel_case
    
// Convert str to PascalCase
str.split('_').map(function (elem) {return elem.slice(0,1).toUpperCase()+elem.slice(1)}).join('')

// Output should be HelloFooBar
Bernard Banta
  • 755
  • 8
  • 14
  • Hi Bernard Banta, thank you for your answer! The community would appreciate if you would extend your answer with the description explaining how the proposed solution works. See [Explaining entirely code-based answers](https://meta.stackoverflow.com/questions/392712/explaining-entirely-code-based-answers) for more details. – mingaleg Feb 07 '23 at 16:41
0

Here is another approach, this one uses reduce:

const snakeToPascal = input =>
  input
    .split("_")
    .reduce(
      (previous, current) =>
        previous + current.charAt(0).toUpperCase() + current.slice(1),
      []
    );
ryan0
  • 1,482
  • 16
  • 21