Skip to content

Instantly share code, notes, and snippets.

@jacks0n
Last active April 19, 2024 04:00
Show Gist options
  • Save jacks0n/e0bfb71a48c64fbbd71e5c6e956b17d7 to your computer and use it in GitHub Desktop.
Save jacks0n/e0bfb71a48c64fbbd71e5c6e956b17d7 to your computer and use it in GitHub Desktop.
Convert a string in JavaScript to Pascal Case (removing non alphabetic 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('');
};
@gnomeria
Copy link

Ouch. Thanks @simonerlandsen

@friedow
Copy link

friedow commented Aug 7, 2020

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;
    }
}

@fullflash
Copy link

you regexp trims out utf characters like şçı

@ilyasakin
Copy link

@fullflash

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