-
-
Save friedow/f5b7e55a29c893b19bc3e82e838e8a5a to your computer and use it in GitHub Desktop.
Convert a string in JavaScript to Pascal Case (removing non alphabetic characters).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode 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