8

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;
}
3
  • 2
    but there is one case that it can't What input does it fail for, and what were you expecting instead? Oct 24, 2018 at 8:09
  • when I'm passing strings like snakeCase it returns snakecase instead of snake_case - so basically it fails on every camelCase string
    – dragi
    Oct 24, 2018 at 8:17
  • Have a look at my answer below @dragi - it should cover all your use-cases 👍 Nov 25, 2020 at 11:03

7 Answers 7

22

You need to be able to detect the points at which an uppercase 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'));

4
  • 1
    Can this be expanded to avoid adding a _ when consecutive uppercase letters are encountered? One problem is when you call snakeCase('CustomerID') the result is customer_i_d, when simply customer_id is prefered.
    – h0r53
    Feb 3, 2020 at 16:33
  • 1
    I got it to work with this, but it seems excessive. const s7 = string => { return string.replace(/\W+/g, " ") .split(/ |\B(?=[A-Z]{2,})/).map(word => word[0] + word.substr(1,).toLowerCase()).join('').split(/ |\B(?=[A-Z])/).map(word => word.toLowerCase()).join('_') };
    – h0r53
    Feb 3, 2020 at 16:57
  • @h0r53 - I just moved the .toLowerCase() to apply to the whole string, before the split: string.toLowerCase().split(...)
    – mheavers
    Sep 15, 2020 at 15:52
  • @mheavers that breaks it working with snakeCase which was the whole point to begin with. Or am I missing something? string.replace(/\W+/g, " ") .toLowerCase() .split(/ |\B(?=[A-Z])/) .map(word => word.toLowerCase()) .join('_'); Nov 25, 2020 at 9:52
5

Let's try that again Stan... this should do snake_case while realising that CamelCASECapitals = camel_case_capitals. It's basically the accepted answer with a pre-filter.

let splitCaps = string => string
    .replace(/([a-z])([A-Z]+)/g, (m, s1, s2) => s1 + ' ' + s2)
    .replace(/([A-Z])([A-Z]+)([^a-zA-Z0-9]*)$/, (m, s1, s2, s3) => s1 + s2.toLowerCase() + s3)
    .replace(/([A-Z]+)([A-Z][a-z])/g, 
        (m, s1, s2) => s1.toLowerCase() + ' ' + s2);
let snakeCase = string =>
    splitCaps(string)
        .replace(/\W+/g, " ")
        .split(/ |\B(?=[A-Z])/)
        .map(word => word.toLowerCase())
        .join('_');
> a = ['CamelCASERules', 'IndexID', 'CamelCASE', 'aID', 
       'theIDForUSGovAndDOD', 'TheID_', '_IDOne']

> _.map(a, snakeCase)

['camel_case_rules', 'index_id', 'camel_case', 'a_id', 'the_id_for_us_gov_and_dod', 
 'the_id_', '_id_one']

// And for the curious, here's the output from the pre-filter:

> _.map(a, splitCaps)

['Camel case Rules', 'Index Id', 'Camel Case', 'a Id', 'the id For us Gov And Dod', 
 'The Id_', '_id One']
1
  • Thanks for the correction! I’m on my phone so can’t check, but I’d happily take your word for it. I’ve edited my answer to link to yours 😄👍 Nov 9, 2021 at 6:59
4

Suppose the string is Hello World? and you want the returned value as hello_world? (with the character, then follow the below code)

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

Example

snakeCase('Hello World?')
// "hello_world?"

snakeCase('Hello & World')
// "hello_&_world"
1
  • A very nice solution. I went even that far to replace multiple repetitive occurrences of underscore to a single one only: str.replace(/\W+/g, " ").split(/ |\B(?=[A-Z])/).map((word) => word.toLowerCase()).join("_").replace(/(_)(?=\1+)/gm, ""); The replace(/(_)(?=\1+)/gm, "") replaces "____" into a single "_". E.g. "Hello_World" would resolve in "hello_world" instead of "hello__world"
    – Advena
    Nov 5, 2021 at 7:59
2

It turns out this answer isn’t foolproof. The fool, being me ;-) Please check out a better one by Orwellophile here: Convert different strings to snake_case in JavaScript

——

I think this one should cover all the bases 😄

It was inspired by @h0r53's answer to the accepted answer. However, it evolved into a more complete function, as it will convert any string, camelCase, kebab-case or otherwise into snake_case the way you'd expect it, containing only a-z and 0-9 characters, usable for function and variable names:

convert_to_snake_case(string) {
    return string.charAt(0).toLowerCase() + string.slice(1) // Lowercase the first character
      .replace(/\W+/g, " ") // Remove all excess white space and replace & , . etc.
      .replace(/([a-z])([A-Z])([a-z])/g, "$1 $2$3") // Put a space at the position of a camelCase -> camel Case
      .split(/\B(?=[A-Z]{2,})/) // Now split the multi-uppercases customerID -> customer,ID
      .join(' ') // And join back with spaces.
      .split(' ') // Split all the spaces again, this time we're fully converted
      .join('_') // And finally snake_case things up
      .toLowerCase() // With a nice lower case
  }

Conversion examples:

'snakeCase'                  => 'snake_case'
'CustomerID'                 => 'customer_id'
'GPS'                        => 'gps'
'IP-address'                 => 'ip_address'
'Another & Another, one too' => 'another_another_one_too'
'random ----- Thing123'      => 'random_thing123'
'kebab-case-example'         => 'kebab_case_example'
1
  • 1
    fails on aID, TheONE, and many others. Sorry :) You can pull apart my answers for faults if it helps any :p Nov 8, 2021 at 2:48
1

There is method in Lodash named snakeCase(). You can consider that as well.

_.snakeCase([string=''])

0

Orwellophile's answer does not work for uppercase words delimited by a space: E.g: 'TEST CASE' => t_e_s_t_case

The following solution does not break consecutive upper case characters and is a little shorter:

const snakeCase = str =>
  str &&
  str
    .match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g)
    .map(x => x.toLowerCase())
    .join('_');

However, trailing underscores after uppercase words (examples from Orwellophile as well), do not work properly. E.g: 'TheID_' => the_i_d

Taken from https://www.w3resource.com/javascript-exercises/fundamental/javascript-fundamental-exercise-120.php.

0

@Orwellophile's answer had a few issues that made it unusable for me.

Here is my solution:

const snakeCase = (string, trim = false, remove_specials = false, underscored_numbers = false) => 
string
    .replace(remove_specials ? /[^A-Za-z0-9_ ]/gm : '', '')
    .replace(/([_ ]+)/gm, '_')
    .replace(trim ? /(^_|_$)/gm : '', '')
    .replace(underscored_numbers ? /([^A-Z0-9_])([^a-z_])/gm : /([^A-Z0-9_])([^a-z0-9_])/gm, (m,preUpper,upper)=> `${preUpper}_${upper}`)
    .replace(underscored_numbers ? /([^0-9_][0-9]|[0-9][^0-9_])/gm : '', (m,i)=> i?i.split('').join('_'):'')
    .replace(/([A-Z])([A-Z])([^A-Z0-9_])/gm, (m,previousUpper,upper,lower)=> `${previousUpper}_${upper}${lower}`)
    .toLowerCase();

It can be provided settings, such as trimming start and end underscores, filtering out non alphanumeric characters, and whether numbers should be treated as separate words or letters.

From what I tested, every scenario seemed to have been handled as it should.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.