Skip to the content.

Snake Case

NPM version NPM downloads Bundle size License: MIT TypeScript

Transform text into snake_case format where words are lowercase and separated by underscores.

๐Ÿš€ Features

๐Ÿ“ฆ Installation

# npm
npm install text-snake-case

# yarn
yarn add text-snake-case

# pnpm
pnpm add text-snake-case

# bun
bun add text-snake-case

๐ŸŽฏ Quick Start

import { snakeCase } from "text-snake-case";

console.log(snakeCase("hello world")); // "hello_world"
console.log(snakeCase("userProfileData")); // "user_profile_data"
console.log(snakeCase("backgroundColor")); // "background_color"

๐Ÿ“– Usage

import { snakeCase } from "text-snake-case";

console.log(snakeCase("hello world")); // "hello_world"

CommonJS

const { snakeCase } = require("text-snake-case");

console.log(snakeCase("hello world")); // "hello_world"

TypeScript

import { snakeCase, snakeCaseTransformMerge, Options } from "text-snake-case";

const result: string = snakeCase("hello world");
console.log(result); // "hello_world"

๐Ÿ”„ Transformation Examples

Basic Transformations

import { snakeCase } from "text-snake-case";

// From different cases
snakeCase("hello world"); // "hello_world"
snakeCase("Hello World"); // "hello_world"
snakeCase("HELLO WORLD"); // "hello_world"
snakeCase("camelCase"); // "camel_case"
snakeCase("PascalCase"); // "pascal_case"
snakeCase("kebab-case"); // "kebab_case"
snakeCase("dot.case"); // "dot_case"
snakeCase("CONSTANT_CASE"); // "constant_case"

// Complex examples
snakeCase("XMLHttpRequest"); // "xml_http_request"
snakeCase("iPhone"); // "i_phone"
snakeCase("version 1.2.3"); // "version_1_2_3"
snakeCase("userProfileData"); // "user_profile_data"

Advanced Options

import { snakeCase, snakeCaseTransformMerge } from "text-snake-case";

// Custom transform to merge numbers without separator
snakeCase("version 1.2.3", {
  transform: snakeCaseTransformMerge,
}); // "version_123"

// Custom word splitting
snakeCase("XMLHttpRequest", {
  splitRegexp: /([a-z])([A-Z])/g,
}); // "xml_http_request"

// Custom character stripping
snakeCase("hello@world.com", {
  stripRegexp: /[@.]/g,
}); // "hello_world_com"

// Custom transformation function
snakeCase("API-v2-endpoint", {
  transform: (word, index) => {
    if (word === "API") return "api";
    if (word === "v2") return "v2";
    return word.toLowerCase();
  },
}); // "api_v2_endpoint"

๐ŸŒ Real-World Examples

Database Column Names

import { snakeCase } from "text-snake-case";

// Table columns
snakeCase("firstName"); // "first_name"
snakeCase("emailAddress"); // "email_address"
snakeCase("createdAt"); // "created_at"
snakeCase("userId"); // "user_id"
snakeCase("accessToken"); // "access_token"

API Field Names

import { snakeCase } from "text-snake-case";

// REST API fields
snakeCase("userProfile"); // "user_profile"
snakeCase("lastLoginDate"); // "last_login_date"
snakeCase("isActive"); // "is_active"
snakeCase("paymentMethod"); // "payment_method"
snakeCase("shippingAddress"); // "shipping_address"

Environment Variables

import { snakeCase } from "text-snake-case";

// Environment variable names
snakeCase("databaseUrl"); // "database_url"
snakeCase("apiKey"); // "api_key"
snakeCase("maxRetries"); // "max_retries"
snakeCase("timeoutMs"); // "timeout_ms"
snakeCase("debugMode"); // "debug_mode"

Object Key Transformation

import { snakeCase } from "text-snake-case";

// Transform object keys from camelCase to snake_case
const jsUser = {
  firstName: "John",
  lastName: "Doe",
  emailAddress: "john@example.com",
  createdAt: "2023-01-01",
};

const dbUser = Object.fromEntries(
  Object.entries(jsUser).map(([key, value]) => [snakeCase(key), value]),
);

console.log(dbUser);
// {
//   first_name: "John",
//   last_name: "Doe",
//   email_address: "john@example.com",
//   created_at: "2023-01-01"
// }

๐Ÿ“– API Reference

snakeCase(input, options?)

Converts a string to snake_case.

Parameters

Returns

Options

interface Options {
  // Custom transform function for word processing
  transform?: (word: string, index: number, words: string[]) => string;

  // Regex to strip characters before processing
  stripRegexp?: RegExp;

  // Custom split function
  split?: (value: string) => string[];
}

snakeCaseTransformMerge

A transform function that merges numeric characters without separation.

import { snakeCase, snakeCaseTransformMerge } from "text-snake-case";

snakeCase("version 1.2.3", { transform: snakeCaseTransformMerge }); // "version_123"

๐Ÿ”ง Advanced Configuration

Custom Word Splitting

import { snakeCase } from "text-snake-case";

// Split on specific patterns
snakeCase("XMLHttpRequest", {
  splitRegexp: /([a-z])([A-Z])/g,
}); // "xml_http_request"

// Split on numbers
snakeCase("user123data", {
  splitRegexp: /([a-zA-Z])(\d)/g,
}); // "user_123_data"

Custom Character Stripping

import { snakeCase } from "text-snake-case";

// Strip specific characters
snakeCase("hello@world.com", {
  stripRegexp: /[@.]/g,
}); // "hello_world_com"

// Strip all non-alphanumeric
snakeCase("hello!@#world", {
  stripRegexp: /[^a-zA-Z0-9]/g,
}); // "hello_world"

Custom Transform Functions

import { snakeCase } from "text-snake-case";

// Preserve specific formatting
snakeCase("XML-HTTP-Request", {
  transform: (word, index) => {
    const acronyms = ["xml", "http", "api", "url"];
    if (acronyms.includes(word.toLowerCase())) {
      return word.toLowerCase();
    }
    return word.toLowerCase();
  },
}); // "xml_http_request"

// Custom business logic
snakeCase("UserV2API", {
  transform: (word, index) => {
    if (word === "V2") return "v2";
    if (word === "API") return "api";
    return word.toLowerCase();
  },
}); // "user_v2_api"

๐Ÿ“Š Bundle Size

This package is optimized for minimal bundle size:

๐ŸŒ Browser Support

๐Ÿงช Testing

# Run tests
pnpm test

# Run tests in watch mode
pnpm test --watch

# Run tests with coverage
pnpm test --coverage

# Type checking
pnpm typecheck

# Linting
pnpm lint

๐Ÿ“œ License

MIT ยฉ Dmitry Selikhov

๐Ÿค Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

๐Ÿ†˜ Support


Made with โค๏ธ by Dmitry Selikhov