I create a new interface for String to add some utility methods using the technique of Monkey-patching.
interface String {
toCamelCase(): string;
}
String.prototype.toCamelCase = function (): string {
return this.replace(/[^a-z ]/gi, '').replace(
/(?:^\w|[A-Z]|\b\w|\s+)/g,
(match: any, index: number) => {
return +match === 0
? ''
: match[index === 0 ? 'toLowerCase' : 'toUpperCase']();
},
);
};
in my controller when I call this new function: toCamelCase :
const str: string = 'this is an example';
const result = str.toCamelCase();
console.log(result);
I have this error :
[Nest] 35664 - ERROR [ExceptionsHandler] str.toCamelCase is not a function TypeError: str.toCamelCase is not a function
what is wrong with this implementation?
Rather than polluting the String prototype, I'd suggest creating a function camelCase(str: string): string that takes in the string you want to camel case and returns it after being camelCased. Something like
export const camelCase = (str: string): string => {
return str.replace(/[^a-z ]/gi, '').replace(
/(?:^\w|[A-Z]|\b\w|\s+)/g,
(match: any, index: number) => {
return +match === 0
? ''
: match[index === 0 ? 'toLowerCase' : 'toUpperCase']();
},
);
}
And now it can be imported like import { camelCase } from './utilties'; and called like camelCase('Hello World!');
This will lead to the function being more standalone, robust, and more easily tested than trying to modify the String prototype, plus, prototype modification isn't common anymore.