or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-lodash-snakecase

The lodash method snakeCase exported as a module for converting strings to snake_case format.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/lodash.snakecase@4.1.x

To install, run

npx @tessl/cli install tessl/npm-lodash-snakecase@4.1.0

index.mddocs/

lodash.snakecase

The lodash method snakeCase exported as a standalone Node.js module for converting strings to snake_case format. This utility transforms camelCase, PascalCase, kebab-case, and space-separated strings into lowercase words connected by underscores, with robust Unicode and internationalization support.

Package Information

  • Package Name: lodash.snakecase
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install lodash.snakecase

Core Imports

var snakeCase = require('lodash.snakecase');

For ES6+ environments with module support:

import snakeCase from 'lodash.snakecase';

Basic Usage

var snakeCase = require('lodash.snakecase');

// Convert camelCase
snakeCase('fooBar');
// => 'foo_bar'

// Convert PascalCase
snakeCase('FooBar');
// => 'foo_bar'

// Convert kebab-case
snakeCase('--FOO-BAR--');
// => 'foo_bar'

// Convert space-separated words
snakeCase('Foo Bar');
// => 'foo_bar'

// Handle complex strings with mixed patterns
snakeCase('XMLHttpRequest');
// => 'xml_http_request'

Capabilities

String Case Conversion

Converts strings to snake_case format by transforming various naming conventions into lowercase words connected by underscores. Handles Unicode characters, accents, and complex string patterns through sophisticated regular expression processing.

/**
 * Converts string to snake case
 * @param {string} [string=''] - The string to convert
 * @returns {string} Returns the snake cased string
 */
function snakeCase(string)

Parameter Details:

  • string (string, optional): The string to convert. Defaults to empty string if not provided or if null/undefined is passed.

Return Value:

  • Returns a string in snake_case format where words are lowercase and separated by underscores.

Behavior:

  • Converts camelCase and PascalCase by inserting underscores before uppercase letters
  • Handles kebab-case, space-separated, and mixed delimiter strings
  • Removes leading/trailing delimiters and normalizes multiple delimiters
  • Processes Unicode characters and diacritical marks (converts "café" to "cafe")
  • Handles complex patterns like acronyms and numbers within strings
  • Returns empty string for null, undefined, or empty input

Comprehensive Examples:

// Basic case conversions
snakeCase('Foo Bar');
// => 'foo_bar'

snakeCase('fooBar'); 
// => 'foo_bar'

snakeCase('FooBar');
// => 'foo_bar'

// Delimiter handling
snakeCase('--FOO-BAR--');
// => 'foo_bar'

snakeCase('foo-bar-baz');
// => 'foo_bar_baz'

snakeCase('foo_bar_baz');
// => 'foo_bar_baz'

// Complex patterns
snakeCase('XMLHttpRequest');
// => 'xml_http_request'

snakeCase('iOS App');
// => 'i_os_app'

snakeCase('HTML5Parser');
// => 'html5_parser'

// Unicode and special characters
snakeCase('café münü');
// => 'cafe_munu'

snakeCase('naïve approach');
// => 'naive_approach'

// Numbers and mixed content
snakeCase('user123ID');
// => 'user123_id'

snakeCase('API2Client');
// => 'api2_client'

// Edge cases
snakeCase('');
// => ''

snakeCase(null);
// => ''

snakeCase(undefined);
// => ''

snakeCase('   ');
// => ''

snakeCase('a');
// => 'a'

Advanced Usage Patterns

Database Column Naming

Convert JavaScript object properties to database-friendly column names:

var snakeCase = require('lodash.snakecase');

var userData = {
  firstName: 'John',
  lastName: 'Doe',
  emailAddress: 'john@example.com',
  phoneNumber: '+1234567890'
};

var dbColumns = {};
Object.keys(userData).forEach(function(key) {
  dbColumns[snakeCase(key)] = userData[key];
});

console.log(dbColumns);
// => {
//   first_name: 'John',
//   last_name: 'Doe', 
//   email_address: 'john@example.com',
//   phone_number: '+1234567890'
// }

API Key Transformation

Transform camelCase API keys to snake_case for external APIs:

var apiKeys = ['userId', 'accessToken', 'refreshToken', 'clientSecret'];
var snakeKeys = apiKeys.map(snakeCase);

console.log(snakeKeys);
// => ['user_id', 'access_token', 'refresh_token', 'client_secret']

Environment Variable Naming

Convert configuration keys to environment variable format:

var configKeys = ['serverPort', 'databaseUrl', 'apiSecret', 'debugMode'];
var envVars = configKeys.map(function(key) {
  return snakeCase(key).toUpperCase();
});

console.log(envVars);
// => ['SERVER_PORT', 'DATABASE_URL', 'API_SECRET', 'DEBUG_MODE']

Form Field Processing

Process form field names for backend APIs:

var formData = {
  'userFirstName': 'Alice',
  'userLastName': 'Smith',
  'contactEmail': 'alice@example.com',
  'preferredLanguage': 'en-US'
};

var processedData = {};
for (var key in formData) {
  processedData[snakeCase(key)] = formData[key];
}

console.log(processedData);
// => {
//   user_first_name: 'Alice',
//   user_last_name: 'Smith',
//   contact_email: 'alice@example.com',
//   preferred_language: 'en-US'
// }

GraphQL Field Mapping

Convert GraphQL field names to match database schema:

var graphqlFields = [
  'createdAt',
  'updatedAt', 
  'isActive',
  'lastLoginTime',
  'userPreferences'
];

var dbFields = graphqlFields.map(snakeCase);

console.log(dbFields);
// => [
//   'created_at',
//   'updated_at',
//   'is_active', 
//   'last_login_time',
//   'user_preferences'
// ]

Error Handling

The snakeCase function is designed to be robust and never throw errors:

  • Handles null and undefined inputs gracefully (returns empty string)
  • Converts non-string inputs to strings before processing
  • Processes invalid Unicode sequences without throwing exceptions
  • Returns predictable output for edge cases like empty strings or whitespace-only strings
// Safe with any input type
snakeCase(123);        // => '123'
snakeCase(true);       // => 'true'  
snakeCase([1, 2, 3]);  // => '1,2,3'
snakeCase({});         // => '[object Object]' -> '[object_object]'