Skip to content

Instantly share code, notes, and snippets.

@friedow
Forked from jacks0n/string-to-pascal-case.js
Last active August 7, 2020 09:06
Show Gist options
  • Save friedow/f5b7e55a29c893b19bc3e82e838e8a5a to your computer and use it in GitHub Desktop.
Save friedow/f5b7e55a29c893b19bc3e82e838e8a5a to your computer and use it in GitHub Desktop.
Convert a string in JavaScript to Pascal Case (removing non alphabetic characters).
declare global {
interface String {
toPascalCase(): string;
}
}
/**
* Convert a string to Pascal Case (removing non alphabetic characters).
*
* @example
* 'hello_world'.toPascalCase() // Will return `HelloWorld`.
* 'fOO BAR'.toPascalCase() // Will return `FooBar`.
*
* @returns {string}
* The Pascal Cased string.
*/
String.prototype.toPascalCase = function(): string {
const words = this.match(/[a-z]+/gi);
if (!words) return "";
return words
.map(function(word) {
return word.charAt(0).toUpperCase() + word.substr(1).toLowerCase();
})
.join("");
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment