Open In App

How to Convert Camel Case String to Snake Case in JavaScript ?

Last Updated : 15 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

We are going to learn about the conversion of camel case string into snake case by using JavaScript. Camel case string means words combined, each starting with uppercase and Snake case means words joined with underscores, all lowercase, Converting camel case to snake case involves transforming strings from a format where words are separated by underscores and letters are lowercase.

Example:

Input: GeeksForGeeks
Output: geeks_for_geeks

Input: CamelCaseToSnakeCase
Output: camel_case_to_snake_case

Several methods can be used to Convert camel case string to snake case in JavaScript, which are listed below:

Approach 1: Using Regular Expression

In this approach we are using the regular expression, which involves using pattern matching to identify uppercase letters in a camel case string, inserting underscores before them, and converting the string to lowercase.

Syntax:

camelCaseString.replace(/([a-z])([A-Z])/g, '$1_$2').toLowerCase();

Example: In this example, we are Converting “GeeksforGeeks” to “geeksfor_geeks” by inserting underscores before uppercase letters and converting to lowercase.

Javascript




let camelCaseString = "GeeksForGeeks";
let snakeCaseString = camelCaseString
    .replace(/([a-z])([A-Z])/g, '$1_$2').toLowerCase();
console.log(snakeCaseString);


Output

geeks_for_geeks

Approach 2: Using Split() and Join() Methods

In this approach, we Split a camel case string using a regex that identifies uppercase letters, join the resulting words with underscores, and convert to lowercase for snake case conversion.

Syntax:

let myStr = camelCaseString.split(/(?=[A-Z])/);
let snakeCaseString = myStr.join('_').toLowerCase();

Example: In this example we are using the above-explained approach.

Javascript




let camelCaseString = "GeeksForGeeks";
let myStr = camelCaseString.split(/(?=[A-Z])/);
let snakeCaseString = myStr.join('_').toLowerCase();
console.log(snakeCaseString);


Output

geeks_for_geeks

Apporach 3: Using Reduce() Method

In this approach, we are using Reduce to Iterate through characters, adding underscores before uppercase ones then join and convert to lowercase for camel to snake case conversion.

Syntax:

array.reduce( function(total, currentValue, currentIndex, arr), initialValue )

Example: In this example we are using reduce() method to convert camel case string into snake case string.

Javascript




const camelCaseString = "GeeksForGeeks";
const snakeCaseString = camelCaseString.split('').reduce(
    (result, val) => {
        if (val === val.toUpperCase()) {
            result += '_';
        }
        return result + val.toLowerCase();
    }, '');
console.log(snakeCaseString);


Output

_geeks_for_geeks

Approach 4: Using for Loop

In this approach, Using a Loop to Iterates through characters, adds underscores before uppercase (except first), and converts to lowercase, creating a snake case string from camel case in JavaScript.

Syntax:

for (statement 1 ; statement 2 ; statement 3){
code here...
};

Example: In this example we are using the above-explained approach.

Javascript




function conversionFunction(str) {
    let snakeCase = '';
    for (let i = 0; i < str.length; i++) {
        if (i > 0 && str[i] === str[i].toUpperCase()) {
            snakeCase += '_' + str[i].toLowerCase();
        } else {
            snakeCase += str[i].toLowerCase();
        }
    }
    return snakeCase;
}
 
let camelCaseString = "GeeksForGeeks";
let snakeCaseString = conversionFunction(camelCaseString);
console.log(snakeCaseString);


Output

geeks_for_geeks

Approach 5: Using Array Map and Join() Method

In this approach, we Splits camel case string into words, each word is converted to lowercase using the map function, and joins with underscores for snake case conversion.

Syntax:

let snakeCaseArray = myStr.map(word => word.toLowerCase());

Example: In this example we are using the above-explained approach.

Javascript




let camelCaseString = "GeeksForGeeks";
 
let myStr = camelCaseString.split(/(?=[A-Z])/);
let snakeCaseArray = myStr.map(word => word.toLowerCase());
let snakeCaseString = snakeCaseArray.join('_');
 
console.log(snakeCaseString);


Output

geeks_for_geeks

Approach 6: Using Lodash _.snakeCase() Method

Lodash _.snakeCase() method is used to convert a string to a snake case. Snake case refers to combining words into a lowercase string with underscores(_) between words. The string can be space-separated, dash-separated, or can be separated by underscores.

Syntax:

_.snakeCase( [string=''] );

Javascript




const _ = require("lodash");
  
// Use of _.snakeCase() method
console.log(_.snakeCase('GeeksForGeeks'));


Output:

'geeks_for_geeks'


Similar Reads

How to convert camel case to snake case in JSON response implicitly using Node.js ?
Camel case and snake case are two common conventions for naming variables and properties in programming languages. In camel case, compound words are written with the first word in lowercase and the subsequent words capitalized, with no spaces or underscore between them. For example, firstName is written in camel case. In snake case, compound words
5 min read
How to Convert Camel Case to Snake Case in PHP ?
Given a Camel Case String, the task is to convert the Camel Case String to a Snake Case String in PHP. Examples: Input: GeeksForGeeksOutput: geeks_for_geeksInput: WelcomeToGfg Output: welcome_to_gfgCamel case uses capital letters at the beginning of each word except the first one, while snake case separates words with underscores and uses all lower
1 min read
How to convert string to camel case in JavaScript ?
We will be given a string and we have to convert it into the camel case. In this case, the first character of the string is converted into lowercase, and other characters after space will be converted into uppercase characters. These camel case strings are used in creating a variable that has meaning. Example of converting string to camel case in J
4 min read
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: GeeksForGeeks Output: geeks_for_geeks Input: CamelCaseToSnakeCase Output: camel_case_to_snake_caseThere are some common approaches: Table of Content Using match(), map(),
2 min read
How to convert hyphens to camel case in JavaScript ?
Given a string containing hyphens (-) and the task is to convert hyphens (-) into camel case of a string using JavaScript. Approach: Store the string containing hyphens into a variable.Then use the RegExp to replace the hyphens and make the first letter of words upperCase. Example 1: This example converts the hyphens ('-') into camel case by using
2 min read
Converting all keys into snake case in multidimensional array in PHP
In the Snake case, we need to convert a given sentence or a word to a style of writing where all upper case characters will be replaced with lower case and all the gaps will be replaced with an underscore(_). In this article, we will see how to find the snake case of the all keys of a given array. Here, we need to check each of the elements present
4 min read
Snake Like Effect using CSS and JavaScript
In this article, we will see how to create a Snake Like Effect by using CSS and JavaScript. CDN Link: Include the following GSAP library in your HTML code. &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.6.0/gsap.min.js"&gt;&lt;/script&gt; Approach : We have taken a div tag named snake which is an instance of the full snake. We have t
2 min read
Javascript Program to Print matrix in snake pattern
Given n x n matrix In the given matrix, you have to print the elements of the matrix in the snake pattern. Examples: Input :mat[][] = { {10, 20, 30, 40}, {15, 25, 35, 45}, {27, 29, 37, 48}, {32, 33, 39, 50}}; Output : 10 20 30 40 45 35 25 15 27 29 37 48 50 39 33 32 Input :mat[][] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; Output : 1 2 3 6 5 4 7 8 9 Reco
2 min read
Create a snake game using HTML, CSS and JavaScript
Snake Game is a single-player game where the snake gets bigger by eating the food and tries to save itself from the boundary of the rectangle and if the snake eats their own body the game will be over. Game Rules:If the snake goes out of the boundary or eats its own body the game will be over.Prerequisites:HTMLCSSJavaScriptApproachSelect the board
4 min read
How to convert a string into kebab case using JavaScript ?
Given a string with space-separated or camel case or snake case letters, the task is to find the kebab case of the following string. Examples: Input: Geeks For GeeksOutput: geeks-for-geeksInput: GeeksForGeeksOutput: geeks-for-geeksInput: Geeks_for_geeksOutput: geeks-for-geeksBelow are the approaches used to convert a string into a kebab case using
3 min read