utilcn logoutilcn
String Utilities

toSnakeCase

Converts a string to snake_case with proper acronym handling

Usage

import { toSnakeCase } from '@/lib/to-snake-case';

const result = toSnakeCase("Hello World");
console.log(result); // "hello_world"

Installation

pnpm dlx shadcn@latest add https://utilcn.dev/r/to-snake-case.json
bunx --bun shadcn@latest add https://utilcn.dev/r/to-snake-case.json
npx shadcn@latest add https://utilcn.dev/r/to-snake-case.json
yarn shadcn@latest add https://utilcn.dev/r/to-snake-case.json

Parameters

ParameterTypeDescription
strstringThe input string

Returns

string - The snake_cased string.

Examples

toSnakeCase("Hello World"); // "hello_world"
toSnakeCase("XMLHttpRequest"); // "xml_http_request"
toSnakeCase("user-name"); // "user_name"
toSnakeCase("APIResponse"); // "api_response"
toSnakeCase("HTML Parser"); // "html_parser"

Implementation

export function toSnakeCase(str: string): string {
  return (
    str
      // Split acronym groups (e.g. "XMLHttp" -> "XML_Http")
      .replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2')
      // Split between a lowercase/digit and an uppercase (e.g. "testHTTP" -> "test_HTTP")
      .replace(/([a-z\d])([A-Z])/g, '$1_$2')
      // Replace spaces and dashes with underscores
      .replace(/[\s-]+/g, '_')
      .toLowerCase()
      // Remove leading and trailing underscores
      .replace(/^_+|_+$/g, '')
  );
}