Skip to content
Related Articles

Related Articles

Improve Article

How to convert a string to snake case using JavaScript ?

  • Last Updated : 25 Dec, 2020
Geek Week

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:

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it’s lowest price ever!




My Personal Notes arrow_drop_up
Recommended Articles
Page :