Files
30-seconds-of-code/snippets/fromCamelCase.md
2022-06-08 09:34:23 +03:00

921 B

title, tags, expertise, cover, firstSeen, lastUpdated
title tags expertise cover firstSeen lastUpdated
String from camelcase string intermediate blog_images/mountain-lake-cottage.jpg 2017-12-17T17:55:51+02:00 2020-10-22T20:23:47+03:00

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'