Last active
April 19, 2024 04:00
-
-
Save jacks0n/e0bfb71a48c64fbbd71e5c6e956b17d7 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
/** | |
* 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() { | |
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(''); | |
}; |
Ouch. Thanks @simonerlandsen
Nice work @jacks0n, thanks for sharing this helped me a great deal!
You should however check whether this.match(/[a-z]+/gi)
might be null. Here is an enhanced version of the original code:
String.prototype.toPascalCase = function() {
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("");
};
And for anyone running typescript, here is a short global declaration for this ;):
declare global {
interface String {
toPascalCase(): string;
}
}
you regexp trims out utf characters like şçı
try this. this regex will also match the extended Latin characters range.
String.prototype.toPascalCase = function() {
const words = this.match(/[a-zA-Z\u00C0-\u024F\u1E00-\u1EFF]+/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
Warning to anyone who wants to use this: This will turn 'HelloWorld' and 'helloWorld' into 'Helloworld'