Skip to content
Related Articles

Related Articles

How to convert a string to snake case using JavaScript ?

Improve Article
Save Article
  • Last Updated : 25 Dec, 2020
Improve Article
Save Article

Given a string in and the task is to write a JavaScript code to convert the given string into snake case and print the modified string. 

Examples:

Input: GeeksForGeeks
Output: geeks_for_geeks
Input: CamelCaseToSnakeCase
Output: camel_case_to_snake_case

We use match(), map(), join, and toLowerCase() method to convert a given string into snake case string. The match() method is used to match the given string with the pattern and then use map() and toLowerCase() method to convert given string into lower case and then use join() method to join the string using underscore (_). 

Example:

HTML




<!DOCTYPE html>
<html>
  
<head>
    <title>
        How to convert a string to
        snake case using JavaScript?
    </title>
</head>
  
<body style="text-align: center;">
    <h1 style="color: green;">
        GeeksforGeeks
    </h1>
  
    <h3>
        How to convert a string to
        snake case using JavaScript?
    </h3>
  
    <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>
</body>
  
</html>

Output:

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!