Home > Web Front-end > JS Tutorial > body text

Convert camelToCase to snake_case in JavaScript

Susan Sarandon
Release: 2024-10-09 18:24:28
Original
904 people have browsed it

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

  // 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"));
Copy after login

Result

> camel_to_case
Copy after login

The above is the detailed content of Convert camelToCase to snake_case in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!