snakeCase
The snake_case utility transforms a string into snake_case format (all lower case with words separated by underscores). It is commonly used for database column names, file naming conventions, or environment variables.
Source Code
View Source Code
ts
import { normalizeCase } from './_caseUtils';
/**
* Converts a string to snake case.
*
* @example
* ```ts
* const text = 'Hello World';
* toSnakeCase(text) // 'hello_world';
* ```
*
* @param str - The string to convert.
*
* @returns The converted string.
*/
export function snakeCase(str: string): string {
return normalizeCase(str, '_').toLowerCase();
}Features
- Isomorphic: Works in both Browser and Node.js.
- Durable Parsing: Handles spaces, dashes, and dots as separators.
- Case Boundary Detection: Correctly splits strings based on transitions between lower and upper case (e.g., from
camelCase).
API
ts
function snakeCase(input: string): string;Parameters
input: The string to transform.
Returns
- The transformed string in
snake_case.
Examples
Basic Conversion
ts
import { snakeCase } from '@vielzeug/toolkit';
snakeCase('hello world'); // 'hello_world'
snakeCase('fooBar'); // 'foo_bar'
snakeCase('Kebab-Case'); // 'kebab_case'
snakeCase('data.meta.id'); // 'data_meta_id'Advanced Scenarios
ts
import { snakeCase } from '@vielzeug/toolkit';
snakeCase(' leading trailing '); // 'leading_trailing'
snakeCase('XMLHttpRequest'); // 'xml_http_request'
snakeCase('multiple---dashes'); // 'multiple_dashes'Implementation Notes
- Trims input and removes leading/trailing separators.
- Collapses consecutive separators into a single underscore.
- Throws
TypeErrorif the input is not a string.
See Also
- camelCase: Convert strings to
camelCase. - kebabCase: Convert strings to
kebab-case. - pascalCase: Convert strings to
PascalCase.