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
All the best π.