re: Object properties: Convert delimited strings to camelCase in JavaScript VIEW POST

FULL DISCUSSION
 

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...

 

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

 

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.

code of conduct - report abuse