首頁 > web前端 > js教程 > 主體

在JavaScript中將camelToCase轉換為snake_case

Susan Sarandon
發布: 2024-10-09 18:24:28
原創
904 人瀏覽過

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"));
登入後複製

Result

> camel_to_case
登入後複製

以上是在JavaScript中將camelToCase轉換為snake_case的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!