const toCamelCase = str => str.replace(/[\._-\s]+(.)?/g, (_, m) => (m ? m.toUpperCase() : ""));
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());
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
Top comments (6)
Let's benchmark.
Or make a part of the string:
'to camel case'.toCamelCase();
Benchmark
Half the time its the original, the other half the new version for me.
Thanks. In Chrome, my version is 25% faster. It was obvious, though. Grouping is a heavy operation.
Thank you, I updated the article and the code.
Perhaps only uppercase letters and use
\w
instead of.
.Sure. You want to write the code for this and we're running it through the benchmarks?