[SOLVED] Convert different strings to snake_case in Javascript

Issue

I know that we have a question similar to this but not quite the same.
I’m trying to make my function work which takes in a string as an argument and converts it to snake_case . It works most of the time with all the fancy !?<>= characters but there is one case that it can’t convert and its camelCase .

It fails when I’m passing strings like snakeCase. It returns snakecase instead of snake_case.

I tried to implement it but I ended up just messing it up even more..

Can I have some help please?

my code:

const snakeCase = string => {
    string = string.replace(/\W+/g, " ").toLowerCase().split(' ').join('_');

    if (string.charAt(string.length - 1) === '_') {
        return string.substring(0, string.length - 1);
    }

    return string;
}

Solution

You need to be able to detect the points at which an upper-case letter is in the string following another letter (that is, not following a space). You can do this with a regular expression, before you call toLowerCase on the input string:

\B(?=[A-Z])

In other words, a non-word boundary, followed by an upper case character. Split on either the above, or on a literal space, then .map the resulting array to lower case, and then you can join by underscores:

const snakeCase = string => {
    return string.replace(/\W+/g, " ")
      .split(/ |\B(?=[A-Z])/)
      .map(word => word.toLowerCase())
      .join('_');
};

console.log(snakeCase('snakeCase'));

Answered By – CertainPerformance

Answer Checked By – Katrina (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.