Convert string to Pascal Case (aka UpperCamelCase) in Javascript


Id like to know how I can covert a string into a pascal case string in javascript (& most probally regex).

Conversion Examples:

  • double-barrel = Double-Barrel
  • DOUBLE-BARREL = Double-Barrel
  • DoUbLE-BaRRel = Double-Barrel
  • double barrel = Double Barrel

Check this link for further info on Pascal Case


s = s.replace(/(\w)(\w*)/g,
        function(g0,g1,g2){return g1.toUpperCase() + g2.toLowerCase();});

The regex finds words (here defined using \w – alphanumerics and underscores), and separates them to two groups – first letter and rest of the word. It then uses a function as a callback to set the proper case.


Alternately, this will also work – a little less regex and more string manipulation:

s = s.replace(/\w+/g,
        function(w){return w[0].toUpperCase() + w.slice(1).toLowerCase();});

I should add this isn’t pascal case at all, since you have word barriers (helloworld vs hello-world). Without them, the problem is almost unsolvable, even with a dictionary. This is more commonly called Title Case, though it doesn’t handle words like “FBI”, “the” or “McDonalds”.

Answered By – Kobi

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published