Convert camelToCase to snake_case in JavaScript
Chinwendu Agbaetuo
Posted on October 9, 2024
Write a function that takes a single string in camelCase format and converts it into a string in snake_case format.
Solution
// A function camelToCase that takes a string (text) as the parameter.
function camelToCase(text) {
// Transform each uppercase letter (character) based on its position.
function upperToUnderScoreLower(character, position) {
// If the letter isn't the first character, add an underscore and convert it to lowercase.
return (position > 0 && "_") + character.toLowerCase();
}
// Replace all uppercase letters in (text) by calling the upperToUnderScoreLower function.
return text.replace(/[A-Z]/g, upperToUnderScoreLower);
}
console.log(camelToCase("camelToCase"));
Result
> camel_to_case
💖 💪 🙅 🚩
Chinwendu Agbaetuo
Posted on October 9, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
javascript The Little Prince [Solution | Javascript] - Computational Thinking 101 | Beginner
January 27, 2021