Convert camelToCase to snake_case in JavaScript

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

// Transf…


This content originally appeared on DEV Community and was authored by Chinwendu Agbaetuo

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 && "_") + match.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


This content originally appeared on DEV Community and was authored by Chinwendu Agbaetuo


Print Share Comment Cite Upload Translate Updates
APA

Chinwendu Agbaetuo | Sciencx (2024-10-09T08:36:36+00:00) Convert camelToCase to snake_case in JavaScript. Retrieved from https://www.scien.cx/2024/10/09/convert-cameltocase-to-snake_case-in-javascript/

MLA
" » Convert camelToCase to snake_case in JavaScript." Chinwendu Agbaetuo | Sciencx - Wednesday October 9, 2024, https://www.scien.cx/2024/10/09/convert-cameltocase-to-snake_case-in-javascript/
HARVARD
Chinwendu Agbaetuo | Sciencx Wednesday October 9, 2024 » Convert camelToCase to snake_case in JavaScript., viewed ,<https://www.scien.cx/2024/10/09/convert-cameltocase-to-snake_case-in-javascript/>
VANCOUVER
Chinwendu Agbaetuo | Sciencx - » Convert camelToCase to snake_case in JavaScript. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/10/09/convert-cameltocase-to-snake_case-in-javascript/
CHICAGO
" » Convert camelToCase to snake_case in JavaScript." Chinwendu Agbaetuo | Sciencx - Accessed . https://www.scien.cx/2024/10/09/convert-cameltocase-to-snake_case-in-javascript/
IEEE
" » Convert camelToCase to snake_case in JavaScript." Chinwendu Agbaetuo | Sciencx [Online]. Available: https://www.scien.cx/2024/10/09/convert-cameltocase-to-snake_case-in-javascript/. [Accessed: ]
rf:citation
» Convert camelToCase to snake_case in JavaScript | Chinwendu Agbaetuo | Sciencx | https://www.scien.cx/2024/10/09/convert-cameltocase-to-snake_case-in-javascript/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.