- Instant help with your JavaScript coding problems

Convert string to snake case in JavaScript

Question:
How to convert string to snake case in JavaScript?
Answer:
function toCamelCase(str){
    return (' ' + str).toLowerCase().replace(/[^a-zA-Z0-9]+(.)/g, (m, chr) => {
        return '_' + chr}).substring(1);
}

console.log(toCamelCase('the name field id     is name-field_id'));
Description:

Snake case (stylized as snake_case) refers to the style of writing in which each space is replaced by an underscore (_ ) character, and the first letter of each word written in lowercase. It is a commonly used naming convention in computing, for example for variable and subroutine names, and for filenames.

To convert a string to a snake case in JavaScript you can use the replace method on the string and use regular expressions and callback functions to generate the right output.

Share "How to convert string to snake case in JavaScript?"