Hi Friends 👋,
Welcome to Infinitbility ❤️!
Today, I’m going to show you how can we convert normal string text to camel case in typescript,
If you are using lodash then you have to just use their available camel case convert method.
1_.camelCase('Foo Bar');2// → 'fooBar'34_.camelCase('--foo-bar--');5// → 'fooBar'67_.camelCase('__FOO_BAR__');8// → 'fooBar
but in this article, we are going to create a custom function that converts text to camelCase text.
So, let’s create it.
Convert string case to camel case
1/**2 * Convert string case to camel case3 *4 * @param str5 * @returns camelcase string6 */7export const camelize = (str: string) => {8 return str.replace(/(?:^\w|[A-Z]|\b\w|\s+)/g, function (match, index) {9 if (+match === 0) return ""; // or if (/\s+/.test(match)) for white spaces10 return index === 0 ? match.toLowerCase() : match.toUpperCase();11 });12};
Now, we have created a function that will return the camelcase string.
let’s see how we can able to use it.
1/**2 * Convert string case to camel case3 *4 * @param str5 * @returns camelcase string6 */7const camelize = (str: string) => {8 return str.replace(/(?:^\w|[A-Z]|\b\w|\s+)/g, function (match, index) {9 if (+match === 0) return ""; // or if (/\s+/.test(match)) for white spaces10 return index === 0 ? match.toLowerCase() : match.toUpperCase();11 });12};1314camelize('FooBar');15// → 'fooBar'1617camelize('foo bar');18// → 'fooBar'
Output

All the best 👍.
Follow me on Twitter
Join our email list and get notified about new content
No worries, I respect your privacy and I will never abuse your email.
Every week, on Tuesday, you will receive a list of free tutorials I made during the week (I write one every day) and news on other training products I create.