How to use Lodash _.snakeCase() method In Javascript

Lodash _.snakeCase() method is used to convert the given string into a snake case string.

Example: below example uses _.snakeCase() method to convert a string to snake case.

JavaScript
const _ = require('lodash');

let myString = 'w3wiki';
let snakeCaseString = _.snakeCase(myString);

console.log(snakeCaseString);

Output:

geeks_for_geeks


How to convert a string to snake case using JavaScript ?

In this article, we are given a string in and the task is to write a JavaScript code to convert the given string into a snake case and print the modified string. 

Examples:

Input: w3wiki
Output: geeks_for_geeks
Input: CamelCaseToSnakeCase
Output: camel_case_to_snake_case

There are some common approaches:

Table of Content

  • Using match(), map(), join(), and toLowerCase()
  • Using for loop
  • Using Lodash _.snakeCase() method

Similar Reads

Using match(), map(), join(), and toLowerCase()

We use the match(), map(), join(), and toLowerCase() methods to convert a given string into a snake case string. The match() method is used to match the given string with the pattern and then use map() and toLowerCase() methods to convert the given string into lower case and then use join() method to join the string using underscore (_)....

Using for loop

In this approach first we initialize empty string to store snake string then we Iterate over each character of the input string and check if the current character is uppercase and not the first character of the string. If so, we will add an underscore (‘_’) before appending the lowercase version of thwill contain the snake case string....

Using Lodash _.snakeCase() method

Lodash _.snakeCase() method is used to convert the given string into a snake case string....