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.
const camelCaseString = "w3wiki";
const snakeCaseString = camelCaseString.split('').reduce(
(result, val) => {
if (val === val.toUpperCase()) {
result += '_';
}
return result + val.toLowerCase();
}, '');
console.log(snakeCaseString);
Output
_geeks_for_geeks
How to Convert Camel Case String to Snake Case in JavaScript ?
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: w3wiki
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:
Table of Content
- Approach 1: Using Regular Expression
- Approach 2: Using Split() and Join() Methods
- Apporach 3: Using Reduce() Method
- Approach 4: Using for Loop
- Approach 5: Using Array Map and Join() Method
- Approach 6: Using Lodash _.snakeCase() Method
Contact Us