DEV Community

Cover image for 1 line of code: How to camelCase a string
martin krause
martin krause

Posted on • Updated on

1 line of code: How to camelCase a string

const toCamelCase = str => str.replace(/[\._-\s]+(.)?/g, (_, m) => (m ? m.toUpperCase() : ""));
Enter fullscreen mode Exit fullscreen mode

Returns a new string in camel case.
Uses space, dot, underscore and dash as delimiter.

Optimised version

const toCamelCase = str => str.replace(/[\s\._-]+\w/g, (m) => m[m.length-1].toUpperCase());
Enter fullscreen mode Exit fullscreen mode

The repository & npm package

You can find the all the utility functions from this series at github.com/martinkr/onelinecode
The library is also published to npm as @onelinecode for your convenience.

The code and the npm package will be updated every time I publish a new article.


Follow me on Twitter: @martinkr and consider to buy me a coffee

Photo by zoo_monkey on Unsplash


Subscribe to the weekly modern frontend development newsletter


Discussion (6)

Collapse
xr0master profile image
Sergey Khomushin • Edited on

Let's benchmark.

const toCamelCase = str => str.replace(/[\s\._-]+\w/g, (m) => m[m.length-1].toUpperCase());
Enter fullscreen mode Exit fullscreen mode

Or make a part of the string: 'to camel case'.toCamelCase();

String.prototype.toCamelCase = function() {return this.replace(/[\s\._-]+\w/g, (m) => m[m.length-1].toUpperCase())}
Enter fullscreen mode Exit fullscreen mode
Collapse
martinkr profile image
martin krause Author

Benchmark
Half the time its the original, the other half the new version for me.

Collapse
xr0master profile image
Sergey Khomushin

Thanks. In Chrome, my version is 25% faster. It was obvious, though. Grouping is a heavy operation.

Thread Thread
martinkr profile image
martin krause Author

Thank you, I updated the article and the code.

Collapse
lexlohr profile image
Alex Lohr

Perhaps only uppercase letters and use \w instead of ..

Collapse
martinkr profile image
martin krause Author

Sure. You want to write the code for this and we're running it through the benchmarks?