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 camel case.
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...
How can I do it?
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;
}
but there is one case that it can't
What input does it fail for, and what were you expecting instead?snakeCase
it returnssnakecase
instead ofsnake_case
- so basically it fails on every camelCase string