Javascript program to convert camel case to snake case

 Camel to Snake Case


Video Solution: https://youtu.be/Q4v17TPFfQE


The company you are working for is refactoring its entire codebase. It's changing all naming conventions from camel to snake case (camelCasing to snake_casing).


Every capital letter is replaced with its lowercase prefixed by an underscore _, except for the first letter, which is lower case without the underscore, so that SomeName becomes some_name.


Task

Write a program that takes in a string that has camel casing, and outputs the same string but with snake casing.


Input Format

A string with camelCasing.


Output Format

The same string but with snake_casing.



Solution: 


cameToSnake.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Camel To Snake</title>
<script src="camelToSnake.js"></script>
</head>
<body>
<input type="text" id="inputValue" />
<button onclick="convert()">Convert</button>
</body>
</html>


camelToSnake.js

function convert() {
const inputValue = document.getElementById('inputValue').value;
const regex = /(?=[A-Z])/;

// first we will convert the given input into string, which is already a string :)
// then we will split the entire string by finding the capital letters according to our regex
// finally we will join those with _ converting entire string to lowercase

alert(inputValue.toString().split(regex).join('_').toLowerCase());
}


Output:





Comments

Popular Posts