Changing the case of a string using JavaScript

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

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

Example

The code for this will be ?

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

The output in the console will be ?

this_is_a_simple_sentence

Alternative Approach Using map()

We can also use the map() method for a more concise solution:

const str = 'Hello World JavaScript';
const toSnakeCase = (str = '') => {
    return str.split(' ')
             .map(word => word.toLowerCase())
             .join('_');
};
console.log(toSnakeCase(str));
hello_world_javascript

Handling Special Characters

For more robust snake case conversion that handles special characters:

const str = 'This-is a Complex_String!';
const toSnakeCase = (str = '') => {
    return str.replace(/[^a-zA-Z0-9]/g, ' ')  // Replace non-alphanumeric with space
             .split(' ')
             .filter(word => word.length > 0)   // Remove empty strings
             .map(word => word.toLowerCase())
             .join('_');
};
console.log(toSnakeCase(str));
this_is_a_complex_string

Conclusion

Snake case conversion can be achieved using split(), toLowerCase(), and join() methods. The map() approach provides cleaner code, while regex handling ensures robust conversion of complex strings.

Updated on: 2026-03-15T23:19:00+05:30

246 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements