Wednesday, October 15, 2025
HomeLanguagesJavascriptHow to convert a string to snake case using JavaScript ?

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: neveropen_for_neveropen
Input: CamelCaseToSnakeCase
Output: camel_case_to_snake_case

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

neveropen_for_neveropen
welcome_to_neveropen_for_neveropen
welcome_to_neveropen_for_neveropen
welcome_to_neveropen_for_neveropen
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11891 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11952 POSTS0 COMMENTS
Shaida Kate Naidoo
6851 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS