JAVASCRIPT
Convert Snake_Case to PascalCase
Transform strings from `snake_case` to `PascalCase` using a powerful regex pattern, perfect for naming conventions in programming languages like JavaScript.
function snakeToPascalCase(snakeCaseString) {
return snakeCaseString
.replace(/_([a-z])/g, (g) => g[1].toUpperCase()) // Convert _x to X
.replace(/^./, (g) => g.toUpperCase()); // Capitalize the first letter
}
console.log(snakeToPascalCase("user_id")); // UserId
console.log(snakeToPascalCase("first_name_last_name")); // FirstNameLastName
console.log(snakeToPascalCase("product_category")); // ProductCategory
console.log(snakeToPascalCase("api_response")); // ApiResponse
console.log(snakeToPascalCase("hello_world")); // HelloWorld
How it works: The `snakeToPascalCase` function converts a string from `snake_case` to `PascalCase`. It uses two `replace` operations with regex: first, `/_([a-z])/g` finds an underscore followed by a lowercase letter and converts that letter to uppercase. Second, `^./` targets the very first character of the string and capitalizes it, resulting in a `PascalCase` format suitable for class or component names.