Open In App

How to convert a string to snake case using JavaScript ?

Improve
Improve
Like Article
Like
Save
Share
Report

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_case

Approach 1: 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 (_). 

Example: This example shows the use of the above-explained approach.

Javascript
<script>
    function snake_case_string(str) {
        return str && str.match(
    /[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g)
            .map(s => s.toLowerCase())
            .join('_');
    }
    
    console.log(snake_case_string('GeeksForGeeks'));
    console.log(snake_case_string('Welcome to GeeksForGeeks'));
    console.log(snake_case_string('Welcome-to-GeeksForGeeks'));
    console.log(snake_case_string('Welcome_to_GeeksForGeeks'));
</script>

Output:

geeks_for_geeks
welcome_to_geeks_for_geeks
welcome_to_geeks_for_geeks
welcome_to_geeks_for_geeks

Approach 2: 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.

Example: below example uses above explained approach.

JavaScript
function toSnakeCase(str) {
    let snakeCase = '';
    for (let i = 0; i < str.length; i++) {
        const char = str[i];
        if (char.toUpperCase() === char && i > 0) {
            snakeCase += '_';
        }
        snakeCase += char.toLowerCase();
    }
    return snakeCase;
}

console.log(toSnakeCase("welcomeToGeeksForGeeks"));

Output
welcome_to_geeks_for_geeks




Last Updated : 20 Mar, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads