Casting a string to snake case - JavaScript


Snake case is basically a style of writing strings by replacing the spaces with '_' and converting the first letter of each word to lowercase.

We are required to write a JavaScript function that takes in a string and converts it to snake case.

Example

Following is the code −

const str = 'This is a simple sentence';
const toSnakeCase = (str = '') => {
   const strArr = str.split(' ');
   const snakeArr = strArr.reduce((acc, val) => {
      return acc.concat(val.toLowerCase());
   }, []);
   return snakeArr.join('_');
};
console.log(toSnakeCase(str));

Output

Following is the output in the console −

this_is_a_simple_sentence

Updated on: 16-Sep-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements