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.

_.camelCase('Foo Bar');
// → 'fooBar'

_.camelCase('--foo-bar--');
// → 'fooBar'

_.camelCase('__FOO_BAR__');
// → '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

/**
 * Convert string case to camel case
 *
 * @param str
 * @returns camelcase string
 */
export const camelize = (str: string) => {
    return str.replace(/(?:^\w|[A-Z]|\b\w|\s+)/g, function (match, index) {
            if (+match === 0) return ""; // or if (/\s+/.test(match)) for white spaces
            return index === 0 ? match.toLowerCase() : match.toUpperCase();
    });
};

Now, we have created a function that will return the camelcase string.

let’s see how we can able to use it.

/**
 * Convert string case to camel case
 *
 * @param str
 * @returns camelcase string
 */
const camelize = (str: string) => {
    return str.replace(/(?:^\w|[A-Z]|\b\w|\s+)/g, function (match, index) {
            if (+match === 0) return ""; // or if (/\s+/.test(match)) for white spaces
            return index === 0 ? match.toLowerCase() : match.toUpperCase();
    });
};

camelize('FooBar');
// → 'fooBar'

camelize('foo bar');
// → 'fooBar'

Output

TypeScript, convert string case to camel case example
TypeScript, convert string case to camel case example

All the best 👍.