How to Convert Camel Case String to Snake Case in JavaScript ?
Last Updated :
27 May, 2024
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);
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);
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);
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);
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);
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 Char to String in JavaScript ? In the article, we are going to learn about conversion Char to a string by using JavaScript, Converting a character to a string in JavaScript involves treating the character as a string, a character is a single symbol or letter, while a string is a sequence of characters. Strings can contain multipl
3 min read
How to Check Case of Letter in JavaScript ? There are different ways to check the case of the letters in JavaScript which are explained below comprehensively, one can choose the method that best suits their specific use case and requirement.Table of ContentUsing the function "toUpperCase()" or "toLowerCase"Using regular expressionUsing ASCII
3 min read
JavaScript Program to Convert String to Bytes In this article, we are going to learn ho to Convert String to bytes in JavaScript. Converting a string to bytes in JavaScript involves encoding the characters using a specific character encoding (such as UTF-8) to represent the string as a sequence of bytes. There are several methods that can be us
3 min read
JavaScript - How to Replace Multiple Characters in a String? Here are the various methods to replace multiple characters in a string in JavaScript.1. Using replace() Method with Regular ExpressionThe replace() method with a regular expression is a simple and efficient way to replace multiple characters.JavaScriptconst s1 = "hello world!"; const s2 = s1.replac
3 min read
JavaScript Program to Swap Characters in a String In this article, We'll explore different approaches, understand the underlying concepts of how to manipulate strings in JavaScript, and perform character swaps efficiently. There are different approaches for swapping characters in a String in JavaScript: Table of Content Using Array ManipulationUsin
6 min read
JavaScript Program to Capitalize the First Letter of Every Sentence in a String In this article, we will see how Capitalizing the first letter of every sentence in a string is a common text manipulation task in JavaScript. It involves identifying sentence boundaries and ensuring that the first letter of each sentence is in uppercase. Examples: Input: "this is Geeks for Geeks we
2 min read
JavaScript Program to Sort Strings in Alphabetical Order Ignoring Case In this article, we are given an array of strings, you need to sort the given array of strings containing both uppercase and lowercase characters in ascending order by ignoring the case in JavaScript. Example 1: Input :- arr = ["Geeks", "for", "geeks", "is", "The", "Best"] Output :- [ 'Best', 'for',
3 min read
JavaScript - String Contains Only Alphabetic Characters or Not Here are several methods to check if a string contains only alphabetic characters in JavaScriptUsing Regular Expression (/^[A-Za-z]+$/) - Most USedThe most common approach is to use a regular expression to match only alphabetic characters (both uppercase and lowercase).JavaScriptlet s = "HelloWorld"
2 min read
JavaScript Program to Add Prefix and Suffix to a String In this article, we are going to implement a JavaScript program through which we can add a prefix and suffix to a given string. A prefix is added to the beginning of a word to modify its meaning. A suffix is added to the end of a word. Together, they form a prefix-suffix string, enabling the creatio
3 min read
JavaScript Program to Mirror Characters of a String Our task is to mirror characters from the N-th position up to the end of a given string, where 'a' will be converted into 'z', 'b' into 'y', and so on. This JavaScript problem requires mirroring the characters in a string starting from a specified position. There are various approaches available to
6 min read