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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With