DEV Community

Object properties: Convert delimited strings to camelCase in JavaScript

Caleb Adepitan on July 19, 2019

Some few months ago, I took a project which was really nice and made me code happily. It was a kind of project that had no dependencies specificall...
Collapse
 
__orderandchaos profile image
Order & Chaos Creative • Edited

Nice walkthrough, thanks for writing it up. I had to work out the opposite yesterday for nearly identical reasons. I wanted to get the key from dataset and make it kebab-cased.

I didn't consider adding a delimiter parameter or doing the reverse as you have. So I've tweaked my code after reading this.

const camelCaseToDelimitedString = (string, delimiter = '-') => 
    string.replace(/([a-z0-9]|(?<!^)(?=[A-Z]))([A-Z])/g, '$1'+delimiter+'$2').toLowerCase();

const delimitedStringToCamelCase = (string, delimiter = '-') =>
    string.replace(new RegExp(delimiter + '([a-z])', 'g'), (m, c) => c.toUpperCase());

/**
 * Examples
 */
console.log(camelCaseToDelimitedString('helloWorld'));
console.log(camelCaseToDelimitedString('helloWorld', '_'));
console.log(camelCaseToDelimitedString('HelloWorld'));
console.log(camelCaseToDelimitedString('HelloWorld', '_'));
console.log(delimitedStringToCamelCase('hello-world'));
console.log(delimitedStringToCamelCase('hello, world', ', '));

Gist: gist.github.com/sarcoma/9df7d82bcc...

Credit where credit is due, I based my conversion off of this gist: gist.github.com/nblackburn/875e6ff...

Collapse
 
calebpitan profile image
Caleb Adepitan

Yeah RegExp is a great approach. I omitted that. I think I should add it. Thanks for sharing this.

Collapse
 
__orderandchaos profile image
Order & Chaos Creative

No problem, Regex is so hard to read, go with whatever works for you. I was lucky enough to find a fairly decently tested Regex match and tweak it to suit my needs.

Thanks again, your post encouraged me to improve my scripts.