简体   繁体   中英

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

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.

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM