Syntax, Parameter and Return Value
Syntax:
_.snakeCase([string=''])
Parameters:
[string=''] (string): The string to convert.
Return Value:
(string) - Returns the snake cased string.
Examples
Converting a Regular String to Snake Case:
JavaScript
var _ = require('lodash');
var text = 'Foo Bar';
console.log(_.snakeCase(text));
You can also try this code with Online Javascript Compiler
Run Code
Output:
'foo_bar'
Demonstrates converting a space-separated string to snake case.
Standardizing Object Keys:
JavaScript
var object = { 'FirstName': 'John', 'LastName': 'Doe' };
var snakeCasedKeysObject = _.mapKeys(object, (value, key) => _.snakeCase(key));
console.log(snakeCasedKeysObject);
You can also try this code with Online Javascript Compiler
Run Code
Output:
{ 'first_name': 'John', 'last_name': 'Doe' }
Shows how to convert object keys to snake case for consistency.
Formatting Strings for Database Fields:
JavaScript
var fieldName = 'UserEmail';
console.log(_.snakeCase(fieldName));
You can also try this code with Online Javascript Compiler
Run Code
Output:
'user_email'
An example of formatting a string to snake case for use as a database field name.
Creating Filenames from Titles:
JavaScript
var title = 'My New Article';
var filename = _.snakeCase(title) + '.txt';
console.log(filename);
You can also try this code with Online Javascript Compiler
Run Code
Output:
'my_new_article.txt'
Demonstrates creating a filename in snake case from a title.
Frequently Asked Questions
How does _.snakeCase() handle non-alphanumeric characters?
_.snakeCase() removes non-alphanumeric characters and uses underscores to separate words.
Can _.snakeCase() handle camelCase and PascalCase strings?
Yes, _.snakeCase() can convert strings from camelCase, PascalCase, and other formats into snake case.
Is _.snakeCase() suitable for all string conversion needs?
_.snakeCase() is ideal for converting strings to snake case. For other naming conventions like camel case or kebab case, different Lodash methods or custom logic would be required.
Conclusion
Lodash's _.snakeCase() method is an effective and straightforward way to convert strings of various formats to snake case. It's particularly useful for standardizing identifiers, creating system-friendly filenames, and ensuring uniformity in text strings across programming contexts.
You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSA, DBMS, Competitive Programming, Python, Java, JavaScript, etc.
Also, check out some of the Guided Paths on topics such as Data Structure and Algorithms, Competitive Programming, Operating Systems, Computer Networks, DBMS, System Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.