String from camelcase

JavaScript, String · Oct 22, 2020

Converts a string from camelcase.

  • Use String.prototype.replace() to break the string into words and add a separator between them.
  • Omit the second argument to use a default separator of _.
const fromCamelCase = (str, separator = '_') =>
  str
    .replace(/([a-z\d])([A-Z])/g, '$1' + separator + '$2')
    .replace(/([A-Z]+)([A-Z][a-z\d]+)/g, '$1' + separator + '$2')
    .toLowerCase();

fromCamelCase('someDatabaseFieldName', ' '); // 'some database field name'
fromCamelCase('someLabelThatNeedsToBeDecamelized', '-');
// 'some-label-that-needs-to-be-decamelized'
fromCamelCase('someJavascriptProperty', '_'); // 'some_javascript_property'
fromCamelCase('JSONToCSV', '.'); // 'json.to.csv'

More like this

  • JavaScript String Casing

    Convert between the most common string casing formats with pure JavaScript and a sprinkle of regular expressions.

    Collection · 7 snippets

  • Camelcase string

    Converts a string to camelcase.

    JavaScript, String · Oct 22, 2020

  • CSV to JSON

    Converts a comma-separated values (CSV) string to a 2D array of objects. The first row of the string is used as the title row.

    JavaScript, String · Jan 30, 2022

  • HSL to object

    Converts an hsl() color string to an object with the values of each color.

    JavaScript, String · Oct 22, 2020