Kieran E
Kieran E

Reputation: 3666

Javascript method for changing snake_case to PascalCase

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);
  }

Upvotes: 10

Views: 12863

Answers (7)

ryan0
ryan0

Reputation: 1525

Here is another approach, this one uses reduce:

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

Upvotes: 0

Bernard Banta
Bernard Banta

Reputation: 755

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

Upvotes: 0

Abhishekh Shakya
Abhishekh Shakya

Reputation: 1

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));

Upvotes: 0

M. Hamza Rajput
M. Hamza Rajput

Reputation: 10246

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

Upvotes: 8

kamoroso94
kamoroso94

Reputation: 1735

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.

Upvotes: 8

Hitmands
Hitmands

Reputation: 14179

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))
;

Upvotes: 1

r3wt
r3wt

Reputation: 4742

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('');
}

Upvotes: 1

Related Questions