Guides

How to Convert String Case: camelCase, snake_case, & Kebab Guide

To convert string casing between camelCase, snake_case, PascalCase, kebab-case, and CONSTANT_CASE, tokenise the source identifier by splitting at word boundaries using regex pattern /([a-z0-9])([A-Z])|[\s_\-]+/g, normalise all extracted word tokens to lowercase, and join them with the target delimiter and capitalization rule.

Naming conventions govern how identifiers, variables, functions, database columns, and CSS selectors are formatted across software engineering ecosystems. When integrating heterogeneous technology stacks—such as connecting a JavaScript frontend using camelCase to a Python REST API expecting snake_case or a SQL database using snake_case—developers frequently need to transform identifier formatting without breaking semantic logic.

Converting strings between letter case formats requires parsing word boundaries created by capital letters, hyphens, underscores, or spaces. This technical guide explains the underlying mechanics of string case transformation, regular expression tokenisation, multi-language casing standards, edge-case resolution, and automated batch refactoring using our 100% private in-browser Case Converter tool.

Key Definitions: camelCase, snake_case, PascalCase, kebab-case, CONSTANT_CASE, Title Case, and Delimiters

Converting identifier strings accurately across programming languages requires understanding seven core casing conventions and structural concepts:

  • camelCase (lowerCamelCase): A convention where words are concatenated without whitespace or punctuation. The first word is written entirely in lowercase, while every subsequent word begins with an uppercase letter (e.g. userFirstName, calculateTotalAmount). Widely used in JavaScript, TypeScript, Java, and Swift.
  • snake_case: A convention where all words are written in lowercase and delimited by single underscores (_) (e.g. user_first_name, calculate_total_amount). Standard in Python, Rust, Ruby, and relational database schemas.
  • PascalCase (UpperCamelCase): A variation of camelCase where every word—including the initial word—starts with a capital letter (e.g. UserFirstName, CalculateTotalAmount). Used for object-oriented class names, type definitions, and component names.
  • kebab-case (dash-case / hyphen-case): A convention where words are written in lowercase and separated by hyphens (-) (e.g. user-first-name, calculate-total-amount). Standard for CSS class names, HTML data attributes, and URL path slugs.
  • CONSTANT_CASE (MACRO_CASE / SCREAMING_SNAKE_CASE): A convention where all characters are converted to uppercase letters and delimited by underscores (_) (e.g. USER_FIRST_NAME, MAX_RETRY_ATTEMPTS). Used to declare global constants, configuration macros, and environment variables.
  • Title Case: A human-readable text presentation where the first letter of major words is capitalized and separated by standard space characters (e.g. User First Name). Used primarily in user interface labels, form headers, and documentation headings.
  • Delimiters: Non-alphanumeric separator characters—such as hyphens (-), underscores (_), periods (.), or whitespace spaces—that mark explicit structural boundaries between word tokens in raw strings.

Why Programming Languages Use Different Naming Conventions (JavaScript vs Python vs CSS vs SQL)

Software ecosystems adopt distinct casing rules based on language syntax constraints, historical design choices, and readability standards. Mixing casing conventions within an ecosystem degrades code maintainability and violates style guidelines.

The primary architectural reasons for casing divergence across major tech stacks include:

  • JavaScript & TypeScript (camelCase & PascalCase): Influenced by Java and ECMAScript standards, JavaScript standardises on camelCase for variable names, object properties, and function declarations (e.g. document.getElementById, addEventListener). PascalCase is strictly reserved for constructor functions, ES6 classes, TypeScript interfaces, and React component names.
  • Python (snake_case & CONSTANT_CASE): Governed by the official PEP 8 style guide, Python mandates snake_case for module names, package identifiers, functions, methods, and instance variables. PascalCase is enforced for class definitions, while CONSTANT_CASE designates module-level constants. Hyphens are invalid in Python identifiers because the interpreter parses - as the subtraction operator.
  • CSS & HTML (kebab-case): HTML and CSS syntax rules favor hyphens to separate words in class attributes, ID selectors, and custom properties (e.g. .user-profile-card, --primary-brand-color). Hyphens improve readability in markup documents. However, when referencing CSS styles via JavaScript DOM objects, browser engines automatically translate kebab-case properties into camelCase (e.g. element.style.backgroundColor maps to background-color).
  • SQL & Relational Databases (snake_case): SQL engines are case-insensitive by default under the ANSI SQL standard (converting unquoted identifiers to uppercase in Oracle/Snowflake or lowercase in PostgreSQL). Using snake_case for database table names and column identifiers avoids identifier quoting issues and maintains portability across PostgreSQL, MySQL, MariaDB, and SQLite.

Anatomy of Casing Conventions: Word Boundaries, Hyphens, Underscores, and Capitalization

Deconstructing an identifier string into its constituent semantic components requires analyzing how word boundaries are expressed. Formally, a compound identifier string $S$ is composed of an ordered sequence of discrete word tokens $W = (w_1, w_2, \dots, w_n)$.

Transforming $S$ from a source casing convention to a target casing convention involves three distinct phases: boundary detection, token extraction, and target formatting.

Word boundaries occur at three structural positions within a raw text string:

  1. Explicit Delimiter Boundaries: Non-alphanumeric characters such as spaces ( ), underscores (_), hyphens (-), or forward slashes (/) explicitly separate tokens (e.g. user_account_id contains explicit _ delimiters).
  2. Implicit CamelHump Boundaries: In camelCase and PascalCase, word transitions are marked by a change from a lowercase letter ($a-z$) or digit ($0-9$) to an uppercase letter ($A-Z$) without any intervening delimiter (e.g. userAccountId transitions from r to A, and t to I).
  3. Acronym Boundaries: Sequences of consecutive uppercase letters represent acronyms or abbreviations. The boundary between an acronym and a subsequent word occurs at the transition from the final uppercase letter of the acronym to a lowercase letter (e.g. in parseHTTPResponse, the boundary separates HTTP and Response).

Once word tokens are extracted, the target casing algorithm applies specific capitalization rules to each token $w_i$ and inserts designated delimiters between adjacent tokens.

Regular Expressions for Word Boundary Splitting and Case Transformation

Robust string casing conversion algorithms rely on regular expressions (regex) to detect implicit and explicit word boundaries. A naive split('_') or split('-') fails when processing camelCase or acronym-laden input strings.

To accurately split any identifier string into lowercase tokens regardless of its original casing, developers use a two-pass tokenisation pattern in JavaScript or Python:

function tokenizeIdentifier(str) {
  return str
    // Step 1: Insert an underscore before capital letters preceded by lowercase letters or digits
    .replace(/([a-z0-9])([A-Z])/g, '$1_$2')
    // Step 2: Insert an underscore between consecutive capital letters and a following lowercase letter (handles acronyms like HTTPResponse -> HTTP_Response)
    .replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2')
    // Step 3: Replace hyphens, spaces, and duplicate delimiters with single underscores
    .replace(/[\s\-]+/g, '_')
    // Step 4: Split by underscore and filter empty tokens
    .toLowerCase()
    .split('_')
    .filter(Boolean);
}

For advanced pattern matching, lookbehind and lookahead assertions allow splitting directly on boundary boundaries without modifying string length:

const boundaryRegex = /(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|[\s_\-]+/;
const words = identifier.split(boundaryRegex).filter(Boolean);

When auditing regex pattern behavior or extracting complex rules for source code parsers, developers can verify expression matches using our Regex Extractor.

Step-by-Step: How to Convert Variable Names Between String Cases

Convert your variable names, object properties, or database column schemas between string cases using these five steps with EasyExtract’s in-browser converter:

  1. Supply Identifier Input or Text Payload: Paste your list of variable names, code snippet, or column list into the Case Converter input panel, or upload your text file.
  2. Execute Tokenisation & Boundary Analysis: The client-side engine executes boundary detection regex algorithms to identify all explicit delimiters (hyphens, underscores, spaces) and implicit CamelHumps transitions.
  3. Normalise Token Array to Lowercase Primitives: The parser extracts discrete word tokens and converts every token character to lowercase, establishing a clean, casing-agnostic token array.
  4. Apply Target Casing Transformation Rules: Select your desired output casing format (e.g. camelCase, snake_case, PascalCase, kebab-case, or CONSTANT_CASE). The engine transforms token initial letters based on the target rules.
  5. Join Tokens with Target Delimiters and Copy: Transformed tokens are concatenated with the target delimiter (e.g. underscores for snake_case, hyphens for kebab-case, or empty string for camelCase) and generated instantly in your output viewport.

Naming Convention Comparison Table

The table below summarizes the six major casing conventions, their delimiter rules, capitalization mechanics, and primary language ecosystems:

Convention Delimiter Capitalization Pattern Primary Ecosystem / Language
camelCase None (empty string) First word lowercase, subsequent words initial-capitalized JavaScript, TypeScript, Java, Swift, REST JSON payloads
snake_case Underscore (_) All words strictly lowercase Python, Rust, Ruby, C, SQL schemas, PostgreSQL
PascalCase None (empty string) All words initial-capitalized (including first word) C#, C++, Java classes, React components, TypeScript types
kebab-case Hyphen (-) All words strictly lowercase CSS selectors, HTML data attributes, URL slugs, Lisp
CONSTANT_CASE Underscore (_) All words strictly uppercase C/C++ macros, Python global constants, environment variables
Title Case Space ( ) Major words initial-capitalized, separated by spaces UI labels, documentation titles, form headers, article titles

Batch Refactoring Variable Names for Database Migrations and REST API Schemas

One of the most common challenges in full-stack web development occurs at the network boundary between frontend applications and backend database layers. Web frontends written in JavaScript or React expect API payloads formatted in camelCase (e.g. userProfilePic), whereas backend ORMs (like Django, SQLAlchemy, or ActiveRecord) and SQL databases require snake_case (e.g. user_profile_pic).

To avoid manually transforming object properties, developers implement recursive key conversion algorithms that automatically translate JSON object payloads during request serialization and response deserialization.

The JavaScript implementation below recursively transforms all keys of a JSON object from snake_case to camelCase:

function convertObjectKeysToCamelCase(obj) {
  if (Array.isArray(obj)) {
    return obj.map(v => convertObjectKeysToCamelCase(v));
  } else if (obj !== null && obj.constructor === Object) {
    return Object.keys(obj).reduce((result, key) => {
      const camelKey = key.replace(/_([a-z0-9])/g, (_, letter) => letter.toUpperCase());
      result[camelKey] = convertObjectKeysToCamelCase(obj[key]);
      return result;
    }, {});
  }
  return obj;
}

Before batch refactoring database migrations or API schemas, developers can inspect payload structures and extract nested property keys using our JSON Field Extractor.

Common Pitfalls: Acronyms (e.g. HTTPResponse), Numbers in Identifiers, and Unicode Accents

Converting string case seems straightforward until edge cases arise. Naive string parsing scripts frequently produce broken variable names when encountering acronyms, embedded numbers, or non-ASCII Unicode characters.

Key technical edge cases and their resolutions include:

  • Acronym Preservation (e.g. HTTPResponse, XMLHTTPRequest): When converting parseHTTPResponse to snake_case, splitting blindly on capital letters yields p_a_r_s_e_h_t_t_p_r_e_s_p_o_n_s_e or parse_h_t_t_p_response. The regex parser must recognize that consecutive uppercase letters belong to a single acronym token, producing parse_http_response or parse_xml_http_request.
  • Numbers and Digits in Identifiers (e.g. v2UserAddress, OAuth2Token): Digits can act as word boundaries depending on context. Converting v2UserAddress to snake_case should produce v2_user_address rather than v_2_user_address. The tokeniser must group alphanumeric tokens appropriately so version numbers and inline digits remain attached to their prefix.
  • Unicode Accents and Diacritics (e.g. caféName, überDriver): Standard ASCII regex classes ([a-z], [A-Z]) fail to match accented characters, stripping or corrupting international strings. Modern casing algorithms utilize Unicode Property Escapes (\p{L} for letters, \p{Lu} for uppercase letters, \p{Ll} for lowercase letters) to preserve diacritics during case transformation:
    const unicodeWordRegex = /\p{Lu}?\p{Ll}+|\p{Lu}+(?!\p{Ll})|\p{N}+/gu;
    const tokens = str.match(unicodeWordRegex);

Privacy & Security: Why Source Code Identifiers Must Stay Local in the Browser

Refactoring proprietary source code, database column names, API schemas, or environment variable definitions requires strict data privacy controls. Pasting source code into online web converter tools that transmit data to remote servers introduces critical security and compliance risks.

Key security implications include:

  • Source Code and IP Exposure: Remote server logs, proxy caches, and third-party telemetry scripts attached to cloud converter websites can store pasted source code snippets, exposing proprietary algorithms and intellectual property.
  • Credential and Secret Leakage: Pasting configuration files containing CONSTANT_CASE environment variable names (such as AWS_SECRET_ACCESS_KEY or DATABASE_URL) can expose internal infrastructure details or credentials if transmitted over the network.
  • Regulatory Compliance Violations: Sending database column schemas containing personal data identifiers (such as ssn_number, user_date_of_birth) to external third-party servers may violate GDPR, HIPAA, or SOC 2 compliance mandates.

EasyExtract’s Case Converter guarantees absolute privacy. All string parsing, regex tokenisation, and casing transformations execute 100% locally within your browser sandbox using client-side JavaScript. Zero byte data is ever transmitted across the network.

Frequently Asked Questions

What is the difference between camelCase and PascalCase?

Both camelCase and PascalCase concatenate words without spaces or delimiters and capitalize the first letter of subsequent words. The sole difference lies in the first letter: camelCase starts with a lowercase letter (e.g. userFirstName), whereas PascalCase starts with an uppercase letter (e.g. UserFirstName). In programming, camelCase is typically used for variables and functions, while PascalCase is reserved for class names, interfaces, and component definitions.

Why does CSS use kebab-case instead of camelCase or snake_case?

CSS specifications adopted kebab-case (e.g. font-size, background-color) to maintain readability in HTML and CSS stylesheets. Hyphens create clear visual word separators in markup documents. While hyphens cannot be used in JavaScript variable names because they collide with the subtraction operator, CSS selectors are parsed in non-computational markup contexts where hyphens are valid characters.

How should acronyms like API, URL, or HTTP be formatted in camelCase?

There are two common conventions for acronyms in camelCase: preserving full uppercase (e.g. parseHTTPResponse, fetchURL) or treating the acronym as a standard word with only the first letter capitalized (e.g. parseHttpResponse, fetchUrl). Modern style guides (such as Google’s Java and TypeScript Style Guides) recommend treating acronyms as words (e.g. fetchUrl) to avoid ambiguous boundaries when multiple acronyms sit adjacent to one another.

How do I convert snake_case keys in a JSON object to camelCase automatically?

You can automatically convert JSON object keys from snake_case to camelCase using a recursive JavaScript function or library like lodash.camelCase. The algorithm iterates over all object properties, replacing regex pattern /_([a-z0-9])/g with the capitalized letter, and recursively applies the transformation to nested arrays and child objects.

Can string casing transformation handle numbers and special characters?

Yes. Robust string casing converters handle numbers by treating digits as part of adjacent word tokens or as standalone numeric tokens (e.g. v2UserAddress converts to v2_user_address). Non-alphanumeric special characters (such as punctuation or symbols) are stripped or treated as explicit word delimiters during the initial tokenisation pass.

Why are database column names usually formatted in snake_case?

Relational database management systems (RDBMS) like PostgreSQL, MySQL, and Oracle are historically case-insensitive under standard SQL rules. If column names are written in camelCase or PascalCase without double quotes, the database engine converts them to lowercase or uppercase automatically, causing query errors. Using snake_case with explicit underscores prevents case-sensitivity issues across all database engines.

Is it safe to convert proprietary source code variable names using online converters?

Converting source code on cloud-based web tools that send text payloads to remote servers exposes confidential code logic and database schemas to server logs and third-party trackers. Using EasyExtract’s 100% client-side Case Converter ensures total security, as all regex parsing and case conversions take place strictly within your local browser memory without uploading data to any server.

Sources & Standards

About Abrar

Abrar builds EasyExtract's free, browser-based extraction tools and writes these guides on getting data out of files — PDFs, spreadsheets, images, archives and Office documents. Every tool runs entirely in your browser, so nothing you open is ever uploaded.

Keep reading